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

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

问题描述

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



下面的代码将在运行时生成异常。 动态对象来自C#类,但它可能是通过DLR从其他语言的对象。点不是如何调用静态方法,而是如何调用无法在C#代码中创建的动态对象的静态方法。

  class Foo 
{
public static int Sum(int x,int y)
{
return x + y;
}
}

类程序
{

static void Main(string [] args)
{
dynamic d = new Foo();
Console.WriteLine(d.Sum(1,3));

}
}

IMHO, / strong>是发明了桥接C#和其他编程语言。还有一些其他语言(例如Java)允许通过对象而不是类型来调用静态方法。



BTW,C#4.0的介绍与C#3.0相比并不如此。

解决方案

这不是直接由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

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

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