How to create a new object instance from a Type

后端 未结 12 1739
孤城傲影
孤城傲影 2020-11-22 03:26

One may not always know the Type of an object at compile-time, but may need to create an instance of the Type.

How do you get a new objec

12条回答
  •  粉色の甜心
    2020-11-22 04:09

    The Activator class within the root System namespace is pretty powerful.

    There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at:

    http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

    or (new path)

    https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance

    Here are some simple examples:

    ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
    
    ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");
    

提交回复
热议问题