简体   繁体   English

使用继承的类作为参数类型覆盖抽象方法

[英]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: 在继承的类中,我想将类本身的类型作为参数T传递,因此我尝试这样做:

public class InheritedClass: BaseClass
{
    ...

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

But intellisense is warning me that 'Type parameter InheritedClass hides class Inherited class' 但是intellisense警告我“类型参数InheritedClass隐藏类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)
    {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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