Using reflection, is it possible to create an instance of a type that inherits from an abstract base class using the abstract base class' constructor? That is, without the inheriting class having a constructor of its own? Somewhat like below, but i开发者_开发知识库t throws an error because you cannot create an instance of an abstract class, of course:
abstract class PersonBase
{
string Name;
public PersonBase(string _name) { Name = _name; }
}
class Person : PersonBase
{
}
public static T GetPerson<T>(string name) where T : PersonBase, new()
{
ConstructorInfo info = typeof(T).BaseType.GetConstructor(new Type[]
{ typeof(string) });
object result = info.Invoke(new object[] { name });
return (T)result;
}
You can make this work by doing new T { (assign properties here) } but of course thats not a constructor, and the properties would have to be public, etc.
The only place it's legal to call an abstract class constructor - whether by reflection or not - is within the constructor of a derived class. So no - as you say, you'd be creating an instance of the abstract type, instead of the concrete type. Imagine if the abstract class had an abstract method, and you called it on whatever the constructor returned - what would that do?
If you can give us more information about what you're trying to achieve, we may be able to help you more.
(Your current example wouldn't even compile, as the default Person
constructor doesn't have a parameterless base class constructor to call.)
精彩评论