2015-10-08 198 views
3


我一直在使用System.Dynamic.ExpandoObject(),創建一個動態的對象現在在某些情況下,某些屬性不能存在,如果試圖訪問這些以這種方式更改System.Dynamic.ExpandoObject默認行爲

myObject.undefinedProperties; 

對象的默認行爲是拋出異常

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

有可能改變這種行爲,在這種情況下返回空值?

回答

4

如果您可以用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 
+0

謝謝這麼多,你解決了我的天! – davidinho

+0

傳入GetDefault(Type類型)的類型似乎總是「對象」,並且永遠不會落入type.IsValueType分支。爲什麼? – WillC

2

ExpandoObject繼承的IDictionary <字符串,對象>這樣你就可以檢查對象具有「undefinedProperties」像這樣

if (((IDictionary<string, object>)myObject).ContainsKey("undefinedProperties")) 
{ 
    // Do something 
}