How to instantiate a type dynamically using reflection?

前端 未结 3 391
抹茶落季
抹茶落季 2021-02-03 23:25

I need to instatiate a C# type dynamically, using reflection. Here is my scenario: I am writing a base class, which will need to instantiate a certain object as a part of its in

3条回答
  •  星月不相逢
    2021-02-04 00:12

    You're looking for Activator.CreateInstance

    object instance = Activator.CreateInstance(myType);
    

    There are are various overloads of this method that can take constructor arguments or other information to find the type (such as names in string form)

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

提交回复
热议问题