简体   繁体   中英

Overriding abstract method with the inherited class as parameter type

I have an abstract class like this:

public abstract class BaseClass
{
    ...

    public abstract void MyMethod<T>(T value);
}

In the inherited classes I want to pass the type of the class itself as the parameter T, so I tried to do this:

public class InheritedClass: BaseClass
{
    ...

    public override void MyMethod<InheritedClass>(InheritedClass value)
    {
        ...
    }
}

But intellisense is warning me that 'Type parameter InheritedClass hides class Inherited class'

What does this message exactly mean? Is there any other way to achieve this?

The error is because your method is creating a generic type with the same name as the class. You cannot specify the generic type for a method when defining it, only when calling it.

Only way to achieve that is to define the generic type on the class so you can specify it when you inherit.

public abstract class BaseClass<T>
{
    public abstract void MyMethod(T value);
}

public class InheritedClass: BaseClass<InheritedClass>
{
    public override void MyMethod(InheritedClass value)
    {
    }
}

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