How to create a new object instance from a Type

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

    Just as an extra to anyone using the above answers that implement:

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

    Be careful - if your Constructor isn't "Public" then you will get the following error:

    "System.MissingMethodException: 'No parameterless constructor defined for this object."

    Your class can be Internal/Friend, or whatever you need but the constructor must be public.

提交回复
热议问题