简体   繁体   中英

Using Activator.CreateInstance() with properties

I have the following property in a base (abstract) class:

protected abstract Type TheType { get; }

The above property is instantiated by child classes:

protected override Type TheType
{
  get { return typeof (ChildClass); }
}

I'd like to instantiate the object in the base class:

var obj = (TheType) Activator.CreateInstance<TheType>();

Unfortunately, I get the following compilation error:

Error   1   'BaseClass.TheType' is a 'property' but is used like a 'type'

How may I invoke Activator.CreateInstance() in this scenario?

PS: I've tried changing the property to a field:

protected Type TheType;

Still I get compilation error:

'BaseClass.TheType' is a 'field' but is used like a 'type'

TheType is a property which returns returns a Type , it is not a Type itself.

Use the Activator.CreateInstance(Type) method instead of the Activator.CreateInstance<T>() method, ie

var obj = Activator.CreateInstance(TheType);

Because you do not know which Type TheType will return, you will be unable to cast it to a specific type at runtime.

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