如何调用在C#4.0的动态类型的静态方法? [英] How to invoke static method in C#4.0 with dynamic type?

查看:170
本文介绍了如何调用在C#4.0的动态类型的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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,但有没有在这个博客帖子一个有趣的解决办法:<一href="http://blogs.msdn.com/davidebb/archive/2009/10/23/using-c-dynamic-to-call-static-members.aspx">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

这篇关于如何调用在C#4.0的动态类型的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆