简体   繁体   中英

How to create or invoke protected constructor of abstract class using reflection?

I am trying to invoke or create instance of abstract class using reflection. Is this possible. This is what I tried, but I get an error saying "Cannot create an instance of abstract class".

Type dynType = myTypes.FirstOrDefault(a => a.Name == "MyAbstractClass");
ConstructorInfo getCons = 
dynType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
object dynamicInstance = getCons.Invoke(null);

EDIT: Can I access properties of this abstract class using reflection?

Calling the constructor on an abstract class is equivalent to trying to instantiate an abstract class, which is not possible (you can not create instances of abstract classes).

What you need to do is create an instance of a derived class and declare its constructor so that it calls the base constructor as in:

public class DerivedClass : AbstractClass
{
    public DerivedClass() : base()
    {
        ....
    }
}

Complete example:

public abstract class Abstract
{
    public Abstract()
    {
        Console.WriteLine("Abstract");
    }
}

public class Derived : Abstract
{
    public Derived() : base()
    {
        Console.WriteLine("Derived");
    }
}

public class Class1
{
    public static void Main(string[] args)
    {
        Derived d = new Derived();
    }
}

The output of this is

Abstract
Derived

You cannot instantiate an abstract class, not even using reflection.

If you need an instance, either:

  • remove the abstract modifier from the class.
  • If you cannot do that (for example, if the class is in a closed library), define a subclass that inherits from the abstract class and instantiate that class.

You cannot create an instance of an abstract class. What you can, though, is to use inheritance and use implicit casting

Derived derived = new Derived();
Abstract abstract = derived;

Through implicit casting you can treat a derived instance like a base-class instance.

From MSDN

The abstract modifier indicates that the thing being modified 
has a missing or incomplete implementation.

See MSDN for a reference.

As already mentioned in all previous answers: its impossible to instantiate abstract class.

Another important note: to instantiate instance by reflection you should use Activator.CreateInstance but not constructor call.

object dynamicInstance = Activator.CreateInstance(yourType, yourArguments);

Object creation is a slightly more complicated process than simply calling constructor. It requires allocation necessary amount of memory and only then setting up object itself by calling constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM