首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在.NET中动态调用类的方法?

如何在.NET中动态调用类的方法?
EN

Stack Overflow用户
提问于 2009-07-13 15:38:19
回答 3查看 23.4K关注 0票数 14

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

喜欢

代码语言:javascript
复制
void caller(string myclass, string mymethod){
    // call myclass.mymethod();
}

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-07-13 15:39:14

您将希望使用反射

下面是一个简单的例子:

代码语言:javascript
复制
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");
    }
}

这是一个非常简单的例子,没有错误检查,也忽略了更大的问题,例如,如果类型驻留在另一个程序集中,那么该怎么办,但我认为这应该会使您走上正确的轨道。

票数 34
EN

Stack Overflow用户

发布于 2009-07-13 15:44:21

就像这样:

代码语言:javascript
复制
public object InvokeByName(string typeName, string methodName)
{
    Type callType = Type.GetType(typeName);

    return callType.InvokeMember(methodName, 
                    BindingFlags.InvokeMethod | BindingFlags.Public, 
                    null, null, null);
}

您应该根据要调用的方法修改绑定标志,并检查msdn中的Type.InvokeMember方法以确定真正需要什么。

票数 9
EN

Stack Overflow用户

发布于 2009-07-13 16:23:20

你为什么要这么做?更有可能的是,您可以在不进行反射的情况下完成此操作,直至并包括动态程序集加载。

票数 -3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1120228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档