如何调用expando对象的成员名称?

时间:2010-12-15 05:31:24

标签: c# expando

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,但这不是一个正确的方法。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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);
    }
}