动态调用方法和类名

Kur*_*ula 9 .net c# class

我有一些情况需要从类名调用方法名称.

string scenario1 = "MockScenario1";
string scenario2 = "MockScenario2";

MockScenario1.GetInfo();
MockScenario2.GetInfo();
Run Code Online (Sandbox Code Playgroud)

如何在这里动态使用字符串来调用方法名称

scenario1.GetInfo()
scenario2.GetInfo()
Run Code Online (Sandbox Code Playgroud)

我试图通过字符串和控制空间找出所有选项来查找相关选项.有什么建议?

我尝试了以下尝试动态生成类名

下面的代码动态生成方法名称

string methodName = "hello";

//Get the method information using the method info class
 MethodInfo mi = this.GetType().GetMethod(methodName);

//Invoke the method
// (null- no parameter for the method call
// or you can pass the array of parameters...)
mi.Invoke(this, null);
Run Code Online (Sandbox Code Playgroud)

更明确的场景:我试图发送类名作为参数MockScenario1和MockScenario2是类名.

string scenarioCats = "MockScenario1";
string scenarioDogs = "MockScenario2";
GetResult(scenarioCats);
GetResult(scenarioDogs);

public static void GetCatsResult(string scenarioCats){
scenarioCats obj = new scenarioCats();
    obj.GetInfo();    
}
public static void GetDogsResult(string scenarioDogs){
scenarioDogs obj = new scenarioDogs();
    obj.GetInfo();    
}
Run Code Online (Sandbox Code Playgroud)

E-B*_*Bat 15

如何从字符串表示形式创建类型的实例:

string scenario1 = "TheNamespace.MockScenario1";
Type theType = this.GetType().Assembly.GetType(scenario1);
var theInstance = (MockScenario1)Activator.CreateInstance(theType);
theInstance.GetInfo();
Run Code Online (Sandbox Code Playgroud)

如果你的类实现了一个通用接口,例如IGetInfoAware,那么你可以写一个更通用的加载器:

var theInstance = (IGetInfoAware)Activator.CreateInstance(theType);
Run Code Online (Sandbox Code Playgroud)

注意:您需要为scenario1和scenario2提供完整的类名

请参阅Activator.CreateInstance

编辑:

正如@Georg指出的那样,如果类型没有在上下文对象的程序集中声明,那么首先需要获取托管类型的程序集:

var theAssembly = (
    from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()
    where (assembly.FullName == "TheNamespace.AssemblyName")
    select assembly
)
.FirstOrDefault();

if ( theAssembly!= null ){
    Type theType = theAssembly.GetType(scenario1);
    var theInstance = (IGetInfoAware)Activator.CreateInstance(theType);
    theInstance.GetInfo();
}
Run Code Online (Sandbox Code Playgroud)

如果由于某种原因您不知道程序集名称,则可以解析类型如下:

public Type GetTypeFromString(String typeName)
{
    foreach (Assembly theAssembly in AppDomain.CurrentDomain.GetAssemblies())
    {
        Type theType = theAssembly.GetType(typeName);
        if (theType != null)
        {
            return theType;                    
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)


Had*_*adi 5

您可以使用反射:

Type thisType = this.GetType();
MethodInfo theMethod =      thisType.GetMethod(FunctionName);
theMethod.Invoke(this, userParameters);
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用命令设计模式。因此,您可以使用哈希映射将字符串存储为哈希映射中的键,然后您的函数将是哈希映射的值。然后当你想调用你的函数时,你可以说 hashmap.get ("yourString")。这将返回您存储为值的函数,您可以从那里调用它。