How to do dynamic object creation and method invocation in .NET 3.5

后端 未结 4 933
广开言路
广开言路 2021-01-06 23:52

How does the code looks that would create an object of class:

string myClass = \"MyClass\";

Of the above type, and then call



        
4条回答
  •  有刺的猬
    2021-01-07 00:22

    • Use Type.GetType(string) to get the type object.
    • Use Activator.CreateInstance(Type) to create an instance.
    • Use Type.GetMethod(string) to retrieve a method.
    • Use MethodBase.Invoke(object, object[]) to invoke the method on the object

    Example, but with no error checking:

    using System;
    using System.Reflection;
    
    namespace Foo
    {
        class Test
        {
            static void Main()
            {
                Type type = Type.GetType("Foo.MyClass");
                object instance = Activator.CreateInstance(type);
                MethodInfo method = type.GetMethod("MyMethod");
                method.Invoke(instance, null);
            }
        }
    
        class MyClass
        {
            public void MyMethod()
            {
                Console.WriteLine("In MyClass.MyMethod");
            }
        }
    }
    

    Each step needs careful checking - you may not find the type, it may not have a parameterless constructor, you may not find the method, you may invoke it with the wrong argument types.

    One thing to note: Type.GetType(string) needs the assembly-qualified name of the type unless it's in the currently executing assembly or mscorlib.

提交回复
热议问题