加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 更改System.Dynamic.ExpandoObject的默认行为

发布时间:2020-12-15 23:28:09 所属栏目:百科 来源:网络整理
导读:我使用System.Dynamic.ExpandoObject()创建了一个动态对象,现在在某些情况下某些属性可能不存在,如果尝试以这种方式访问??这些属性 myObject.undefinedProperties; 对象的默认行为是抛出异常 'System.Dynamic.ExpandoObject' does not contain a definition
我使用System.Dynamic.ExpandoObject()创建了一个动态对象,现在在某些情况下某些属性可能不存在,如果尝试以这种方式访问??这些属性

myObject.undefinedProperties;

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

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

有可能改变这种行为并在这种情况下返回空值吗?

解决方法

如果您可以使用DynamicObject替换ExpandoObject,您可以编写满足您要求的自己的类:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读