[英]How to invoke static method in C#4.0 with dynamic type?
In C#4.0, we have dynamic type, but how to invoke static method of dynamic type object? 在C#4.0中,我们具有动态类型,但是如何调用动态类型对象的静态方法呢?
Below code will generate exception at run time. 下面的代码将在运行时生成异常。 The dynamic object is from C# class, but it could be object from other languages through DLR.
动态对象来自C#类,但也可以是其他语言通过DLR提供的对象。 The point is not how to invoke static method, but how to invoke static method of dynamic object which could not be created in C# code.
关键不是如何调用静态方法,而是如何调用C#代码无法创建的动态对象的静态方法。
class Foo
{
public static int Sum(int x, int y)
{
return x + y;
}
}
class Program
{
static void Main(string[] args)
{
dynamic d = new Foo();
Console.WriteLine(d.Sum(1, 3));
}
}
IMHO, dynamic is invented to bridge C# and other programming language. 恕我直言, 动态被发明来桥接C#和其他编程语言。 There is some other language (eg Java) allows to invoke static method through object instead of type.
还有一些其他语言(例如Java)允许通过对象而不是类型来调用静态方法。
BTW, The introduction of C#4.0 is not so impressive compared to C#3.0. 顺便说一句,与C#3.0相比,C#4.0的引入并不那么令人印象深刻。
C#4不直接支持此功能,但是此博客文章中有一个有趣的解决方法: http : //blogs.msdn.com/davidebb/archive/2009/10/23/using-c-dynamic-to-call-static- Members.aspx
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.