如果您可以用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
謝謝這麼多,你解決了我的天! – davidinho
傳入GetDefault(Type類型)的類型似乎總是「對象」,並且永遠不會落入type.IsValueType分支。爲什麼? – WillC