我有一个使用 System.Dynamic.ExpandoObject() 创建的动态对象,现在在某些情况下某些属性可能不存在,如果尝试以这种方式访问这些属性
myObject.undefinedProperties;
对象的默认行为是抛出异常
'System.Dynamic.ExpandoObject' does not contain a definition for 'undefinedProperties'
是否可以更改此行为并在那种情况下返回空值?
最佳答案
如果您可以将 ExpandoObject
替换为 DynamicObject
,您可以编写自己的类来满足您的要求:
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
关于c# - 更改 System.Dynamic.ExpandoObject 默认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009741/