我使用System.Dynamic.ExpandoObject()创建了一个动态对象,现在在某些情况下,某些属性可能不存在,如果尝试以这种方式访问这些属性
myObject.undefinedProperties;
对象的默认行为是抛出异常
'System.Dynamic.ExpandoObject' does not contain a definition for 'undefinedProperties'
是否可以更改此行为并返回空值?
答案 0 :(得分:4)
如果您可以将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
答案 1 :(得分:2)
ExpandoObject继承IDictionary&lt; string,object&gt;所以你可以检查对象是否有像这样的“undefinedProperties”
if (((IDictionary<string, object>)myObject).ContainsKey("undefinedProperties"))
{
// Do something
}
答案 2 :(得分:1)
您可以在ExpandoObject中测试属性的存在,请参阅此处Detect property in ExpandoObject