更改System.Dynamic.ExpandoObject的默认行为
本文关键字:默认 ExpandoObject System Dynamic 更改 | 更新日期: 2023-09-27 18:16:53
我有一个使用System.dynamic.ExpandoObject((创建的动态对象,现在在某些情况下,一些属性可能不存在,如果尝试以这种方式访问
myObject.undefinedProperties;
对象的默认行为是抛出异常
'System.Dynamic.ExpandoObject' does not contain a definition for 'undefinedProperties'
是否可以更改此行为并在这种情况下返回null值?
如果您可以用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
ExpandoObject继承IDictionary<string,object>这样你就可以检查对象是否有像这个一样的"undefinedProperties">
if (((IDictionary<string, object>)myObject).ContainsKey("undefinedProperties"))
{
// Do something
}
您可以测试ExpandoObject中是否存在属性,请参阅此处检测ExpandoObject中的属性