How to create a new object instance from a Type

后端 未结 12 1888
孤城傲影
孤城傲影 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:12

    ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
    

    The Activator class has a generic variant that makes this a bit easier:

    ObjectType instance = Activator.CreateInstance();
    

提交回复
热议问题