How to instantiate a type dynamically using reflection?

前端 未结 3 380
抹茶落季
抹茶落季 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-03 23:48

    You might want to use generics instead:

    public abstract class MyBaseClass where T : new()
    {
        protected MyBaseClass()
        {
            T myObj = new T();
             // Instantiate object of type passed in 
             /* This is the part I'm trying to figure out */
        }
    }
    
    public class MyDerivedClass : MyBaseClass
    {
        public MyDerivedClass() 
        {
        }
    }
    

    The where T : new() is required to support the new T() construct.

提交回复
热议问题