2011-06-09 30 views

回答

30

是這樣的?

using System; 
using System.Collections.Generic; 
using System.Dynamic; 

public class NullingExpandoObject : DynamicObject 
{ 
    private readonly Dictionary<string, object> values 
     = new Dictionary<string, object>(); 

    public override bool TryGetMember(GetMemberBinder binder, out object result) 
    { 
     // We don't care about the return value... 
     values.TryGetValue(binder.Name, out result); 
     return true; 
    } 

    public override bool TrySetMember(SetMemberBinder binder, object value) 
    { 
     values[binder.Name] = value; 
     return true; 
    } 
} 

class Test 
{ 
    static void Main() 
    { 
     dynamic x = new NullingExpandoObject(); 
     x.Foo = "Hello"; 
     Console.WriteLine(x.Foo ?? "Default"); // Prints Hello 
     Console.WriteLine(x.Bar ?? "Default"); // Prints Default 
    } 
} 

我希望真正的ExpandoObject是相當比這更復雜,但如果這是你所需要的...

+0

感謝Skeetman! – mcintyre321 2011-06-09 11:35:52

+1

無論'values.TryGetValue'中的結果是什麼,都可以返回true來抑制錯誤。謝謝你的答案! – dpp 2013-06-18 10:58:57

+0

不好意思復活這個,但幾年後,這段代碼仍然會產生兩個RuntimeBinderException異常。有沒有什麼辦法可以讓這項工作在每次訪問期間都不會觸發異常? – Anthony 2015-08-14 20:52:33