更改 System.Dynamic.ExpandoObject 默认行为

Change System.Dynamic.ExpandoObject default behavior


我有一个使用 System.Dynamic.ExpandoObject() 创建的动态对象,现在在某些情况下某些属性可能不存在,如果尝试以这种方式访问​​这些属性

myObject.undefinedProperties;

对象的默认行为是抛出异常

'System.Dynamic.ExpandoObject' does not contain a definition for 'undefinedProperties'

是否可以更改此行为并且 return 在这种情况下为空值?

您可以在 ExpandoObject 中测试 属性 是否存在,请参阅此处 Detect property in ExpandoObject

ExpandoObject 继承 IDictionary 所以你可以检查对象是否有 "undefinedProperties" 这样的

if (((IDictionary<string, object>)myObject).ContainsKey("undefinedProperties"))
{
    // Do something
}

如果您可以将ExpandoObject替换为DynamicObject,您可以编写自己的class满足您的要求:

public class MyExpandoReplacement : DynamicObject
{
    private Dictionary<string, object> _properties = new Dictionary<string, object>();
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (!_properties.ContainsKey(binder.Name))
        {
            result = GetDefault(binder.ReturnType);
            return true;
        }

        return _properties.TryGetValue(binder.Name, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        this._properties[binder.Name] = value;
        return true;
    }

    private static object GetDefault(Type type)
    {
        if (type.IsValueType)
        {
            return Activator.CreateInstance(type);
        }
        return null;
    }
}

用法:

dynamic a = new MyExpandoReplacement();
a.Sample = "a";

string samp = a.Sample; // "a"
string samp2 = a.Sample2; // null