Dynamically invoking any function by passing function name as string

后端 未结 5 578
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 03:54

How do I automate the process of getting an instance created and its function executed dynamically?

Thanks

Edit: Need an option to pass parameters too. Thank

5条回答
  •  -上瘾入骨i
    2020-12-01 04:32

    I think your problem is little too generic here, I am providing a solution with certain assumptions here.

    Assumption: you have a typeName (string), methodName (string), and a parameter (of SomeType).

    public static void InvokeMethod(string typeName, string methodName, SomeType objSomeType) {
          Type type = Type.GetType(typeName);
          if(type==null) {
            return;
          }
          object instance = Activator.CreateInstance(type); //Type must have a parameter-less contructor, or no contructor.   
          MethodInfo methodInfo =type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public);
          if(methodInfo==null) {
            return;
          }
          methodInfo.Invoke(instance, new[] { objSomeType });  
        } 
    

    let me know know if my assumptions are wrong.

提交回复
热议问题