简体   繁体   English

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

[英]How to invoke static method in C#4.0 with dynamic type?

In C#4.0, we have dynamic type, but how to invoke static method of dynamic type object? 在C#4.0中,我们具有动态类型,但是如何调用动态类型对象的静态方法呢?

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. 动态对象来自C#类,但也可以是其他语言通过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. 关键不是如何调用静态方法,而是如何调用C#代码无法创建的动态对象的静态方法。

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. 恕我直言, 动态被发明来桥接C#和其他编程语言。 There is some other language (eg Java) allows to invoke static method through object instead of type. 还有一些其他语言(例如Java)允许通过对象而不是类型来调用静态方法。

BTW, The introduction of C#4.0 is not so impressive compared to C#3.0. 顺便说一句,与C#3.0相比,C#4.0的引入并不那么令人印象深刻。

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

While C# doesn't support it, the DLR does. 尽管C#不支持,但DLR支持。 You can programmatically access the dlr calls with Dynamitey 您可以使用Dynamitey以编程方式访问dlr调用

var staticContext = InvokeContext.CreateStatic ;

Console.WriteLine(Dynamic.InvokeMember(staticContext(typeof(Foo)), "Sum", 1,3));

One possible workaround would be to use reflection. 一种可能的解决方法是使用反射。

dynamic d = new Foo();

var sum = (int)d.GetType()
                .GetMethod("Sum")
                .Invoke(d, new object[] { 1, 3 });
Console.WriteLine(sum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 WPF中的C#4.0 GetWindowRect - C#4.0 GetWindowRect in wpf 如何使用 C#4.0 在 contextmenustrip 中添加子菜单项? - How to add sub menu items in contextmenustrip using C#4.0? 使用C#4.0中的默认值反映构造函数 - Reflecting constructors with default values in C#4.0 在属性网格c#4.0中级联组合框 - cascading combobox in a propertygrid c#4.0 C#4.0:如何确定类型是否共同变化 - C#4.0: How to find out if types are co-variantly equal 如何在Mono和Visual Studio 2010(C#4.0)上跳过延迟签名组件的强名称验证? - how to skip the strong name verification for delay signed assembilies on Mono and Visual studio 2010(C#4.0)? 如何使用自动换行功能在 C#4.0 中动态设置 label 框的文本? - How to set a text of label box dynamically in C#4.0 with word Wrap functionality? 如何使用C#4.0访问为Visio 2010使用Ribbon.xml创建的自定义选项卡/按钮 - How to Access Custom tab/buttons created using Ribbon.xml for Visio 2010 using C#4.0 如何使用C#4.0从xml内容中删除特定的xml元素? - how to remove specific xml elements from the xml content using C#4.0? 如何使用C#4.0 Win Form Application隐藏TreeView控件中某个TreeNode的复选框? - How to hide checkbox of the certain TreeNode in TreeView control using C#4.0 Win Form Application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM