如果动态对象不包含属性,则获取默认值

Car*_* G. 5 .net c# dynamic

当使用多种语言处理动态对象时,有一种结构可让您获取属性的值,如果所述属性不存在,则返回默认值。

我想知道在.NET中使用动态时是否存在类似的方法/语法。我知道您可以将ExpandoObject强制转换为Dictionary,但是有时不能保证动态对象是Expando。

我在想一些与以下代码具有相同效果的东西

public class SomeClass
{
    public string ValidProperty { get; set; }
}

dynamic t = new SomeClass() { 
    ValidProperty = "someValue"
};

Console.WriteLine(t.Get("ValidProperty", "doesn't exist")); // Prints 'someValue'
Console.WriteLine(t.Get("InvalidProperty", "doesn't exist")); // Prints 'doesn't exist'
Run Code Online (Sandbox Code Playgroud)

DVK*_*DVK 1

如果您谈论 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;
    }
Run Code Online (Sandbox Code Playgroud)

如果动态不是 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);
    }
Run Code Online (Sandbox Code Playgroud)