如何在 .NET 中动态调用类的方法? [英] How to dynamically call a class' method in .NET?

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

问题描述

如何将类和方法名称作为字符串传递并调用该类的方法?

How to pass a class and a method name as strings and invoke that class' method?

喜欢

void caller(string myclass, string mymethod){
    // call myclass.mymethod();
}

谢谢

推荐答案

您需要使用 反射.

这是一个简单的例子:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        caller("Foo", "Bar");
    }

    static void caller(String myclass, String mymethod)
    {
        // Get a type from the string 
        Type type = Type.GetType(myclass);
        // Create an instance of that type
        Object obj = Activator.CreateInstance(type);
        // Retrieve the method you are looking for
        MethodInfo methodInfo = type.GetMethod(mymethod);
        // Invoke the method on the instance we created above
        methodInfo.Invoke(obj, null);
    }
}

class Foo
{
    public void Bar()
    {
        Console.WriteLine("Bar");
    }
}

现在这是一个非常的例子,没有错误检查,也忽略了更大的问题,比如如果类型存在于另一个程序集中该怎么办,但我认为这应该让你走上正确的轨道.

Now this is a very simple example, devoid of error checking and also ignores bigger problems like what to do if the type lives in another assembly but I think this should set you on the right track.

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

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