ExpandoObjects, . , IDictionary , , . .
public static T PropertyOrDefault<T>(this ExpandoObject obj, string propertyName)
{
var dynamicAsDictionary = (IDictionary<string, object>)obj;
if (!dynamicAsDictionary.ContainsKey(propertyName))
{
return default(T);
}
object propertyValue = dynamicAsDictionary[propertyName];
if (!(propertyValue is T))
{
return default(T);
}
return (T)propertyValue;
}
ExpandoObject, .
public static T PropertyOrDefault<T>(dynamic obj, string propertyName)
{
if (obj is ExpandoObject)
{
return ((ExpandoObject)obj).PropertyOrDefault<T>(propertyName);
}
Type objectType = obj.GetType();
PropertyInfo p = objectType.GetProperty(propertyName);
if (p != null)
{
object propertyValue = p.GetValue(obj);
if (propertyValue is T)
{
return (T)propertyValue;
}
}
return default(T);
}