ObjectExtensions
Some methods for working with bare objects.
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());
foreach (PropertyInfo propertyInfo in properties) {
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;
}
}
}