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

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

问题描述

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

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

下面的代码会在运行时产生异常.动态 对象来自 C# 类,但它可以是通过 DLR 来自其他语言的对象.关键不在于如何调用静态方法,而在于如何调用无法在C#代码中创建的动态对象的静态方法.

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

    }
}

恕我直言,dynamic 是为了连接 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#3.0 相比,C#4.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

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

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