且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-15 15:14:15

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


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

    }
}

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.

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

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