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