2010-12-15 43 views
1
dynamic test = new ExpandoObject(); 
test.A = "ok"; 

try{ 
    Console.WriteLine(test.B); 
} 
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex){ 
    // how can i know that B was invoke? 
} 

如上面的代碼,test.B不是'test'的成員。但我怎麼知道'B'正在呼叫。我發現的唯一方法是查看ex.Message,但這不是一個正確的方法。使用如何獲取調用expando對象的成員名稱?

回答

2

如果使用DynamicObject代替ExpandoObject它會更容易。

class MyDynamicObject : DynamicObject 
{ 
    public override bool TryGetMember(GetMemberBinder binder, out object result) 
    { 
     Console.WriteLine(binder.Name); 
     //simply prints the name, you can raise an event here or something else 
     return base.TryGetMember(binder, out result); 
    } 
} 
2

嘗試StackFrame

catch (Exception e) 
{ 
    StackTrace st = new StackTrace(); 
    StackTrace st1 = new StackTrace(new StackFrame(true)); 
    Console.WriteLine(" Stack trace for Method1: {0}", 
     st1.ToString()); 
    Console.WriteLine(st.ToString()); 
    throw e; 
}