ObjectExtensions
Some methods for working with bare objects.
using AngleSharp.Attributes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace AngleSharp.Extensions
{
[DebuggerStepThrough]
internal static class ObjectExtensions
{
public static Dictionary<string, T> ToDictionary<T>(this object values, Func<object, T> converter)
{
Dictionary<string, T> dictionary = new Dictionary<string, T>();
if (values != null) {
PropertyInfo[] properties = PortableExtensions.GetProperties(values.GetType());
PropertyInfo[] array = properties;
foreach (PropertyInfo propertyInfo in array) {
object arg = propertyInfo.GetValue(values, null) ?? string.Empty;
dictionary.Add(propertyInfo.Name, converter(arg));
}
}
return dictionary;
}
public static Dictionary<string, object> ToDictionary(this object values)
{
return values.ToDictionary((object m) => m);
}
public static T? TryGet<T>(this IDictionary<string, object> values, string key) where T : struct
{
if (values.TryGetValue(key, out object value) && value is T)
return (T)value;
return null;
}
public static object TryGet(this IDictionary<string, object> values, string key)
{
if (values.TryGetValue(key, out object value))
return value;
return null;
}
public static U GetOrDefault<T, U>(this IDictionary<T, U> values, T key, U defaultValue)
{
if (!values.TryGetValue(key, out U value))
return defaultValue;
return value;
}
public static double Constraint(this double value, double min, double max)
{
if (!(value < min)) {
if (!(value > max))
return value;
return max;
}
return min;
}
public static string GetMessage<T>(this T code) where T : struct
{
DomDescriptionAttribute customAttribute = typeof(T).GetTypeInfo().GetDeclaredField(code.ToString()).GetCustomAttribute<DomDescriptionAttribute>();
if (customAttribute != null)
return customAttribute.Description;
return "An unknown error occurred.";
}
}
}