How to invoke static method in C#4.0 with dynamic type?

后端 未结 3 2176
栀梦
栀梦 2020-12-11 01:26

In C#4.0, we have dynamic type, but how to invoke static method of dynamic type object?

Below code will generate exception at run time. The dynamic

相关标签:
3条回答
  • 2020-12-11 02:17

    One possible workaround would be to use reflection.

    dynamic d = new Foo();
    
    var sum = (int)d.GetType()
                    .GetMethod("Sum")
                    .Invoke(d, new object[] { 1, 3 });
    Console.WriteLine(sum);
    
    0 讨论(0)
  • 2020-12-11 02:18

    This is not supported directly by C# 4 but there's an interesting workaround in this blog post: http://blogs.msdn.com/davidebb/archive/2009/10/23/using-c-dynamic-to-call-static-members.aspx

    0 讨论(0)
  • 2020-12-11 02:21

    While C# doesn't support it, the DLR does. You can programmatically access the dlr calls with Dynamitey

    var staticContext = InvokeContext.CreateStatic ;
    
    Console.WriteLine(Dynamic.InvokeMember(staticContext(typeof(Foo)), "Sum", 1,3));
    
    0 讨论(0)
提交回复
热议问题