简体   繁体   中英

Inherit from a class that has a generic type

I have a class with a generic type

class GenericClass<T> where T : new()
{
    public T GenericType;

    public GenericClass()
    {
        GenericType = new T();
    }
}

I now want to create new classes that inherit from my GenericClass but passing the new class in as the type.

so...

class Class1:GenericClass<Class1>
{
    public string Class1Property { get; set; }
}

class Class2 : GenericClass<Class2>
{
    public string Class2Property { get; set; }
}

If I do this and then create a new instance of Class 1 the code goes into an infinite loop.

Class1 c1 = new Class1();

Is what I'm trying to do possible?

The line of

GenericType = new T();

in your base constructor is calling the constructor for the inheriting type, which calls the base constructor, which continues the loop.

If you are just trying to track the type of the class that inherited, try a

typeof(T);

or

this.GetType();

as they get you the type, without creating a new instance of the type.

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