如何调用在C#4.0的动态类型的静态方法?静态、类型、方法、动态

2023-09-04 00:14:48 作者:初尘

在C#4.0中,我们有动态类型,但如何调用动态类型对象的静态方法?

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

下面code则会产生异常运行时。在动态对象是从C#类,但它可能是由德国航空航天中心通过其他语言的对象。问题的关键不在于如何调用静态方法,但如何调用动态这可能不是在C#code创建对象的静态方法。

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. 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.

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));

    }
}

恕我直言,动态的发明填补C#等编程语言。还有一些其他的语言(如Java的)允许通过对象,而不是类型调用静态方法。

IMHO, dynamic is invented to bridge C# and other programming language. There is some other language (e.g. Java) allows to invoke static method through object instead of type.

顺便说一句,对C#4.0的推出是不是这样的IM pressive相比,C#3.0。

BTW, The introduction of C#4.0 is not so impressive compared to C#3.0.

推荐答案

这是不直接支持C#4,但有没有在这个博客帖子一个有趣的解决办法:http://blogs.msdn.com/davidebb/archive/2009/10/23/using-c-dynamic-to-call-static-members.aspx

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