Dynamically invoking any function by passing function name as string

后端 未结 5 584
佛祖请我去吃肉
佛祖请我去吃肉 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:36

    Do you just want to call a parameterless constructor to create the instance? Is the type specified as a string as well, or can you make it a generic method? For example:

    // All error checking omitted. In particular, check the results
    // of Type.GetType, and make sure you call it with a fully qualified
    // type name, including the assembly if it's not in mscorlib or
    // the current assembly. The method has to be a public instance
    // method with no parameters. (Use BindingFlags with GetMethod
    // to change this.)
    public void Invoke(string typeName, string methodName)
    {
        Type type = Type.GetType(typeName);
        object instance = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod(methodName);
        method.Invoke(instance, null);
    }
    

    or

    public void Invoke(string methodName) where T : new()
    {
        T instance = new T();
        MethodInfo method = typeof(T).GetMethod(methodName);
        method.Invoke(instance, null);
    }
    

提交回复
热议问题