繁体   English   中英

在接口中使用基类

[英]using base class in interface

我有一个基类:

class BaseClass{ }

我想实现使用基类的接口:

public interface IClass
{
   BaseClass GetValue();
}

然后创建实现此接口的子类,但是在方法中返回了自己的类类型:

class Child: BaseClass, IClass
{
   Child GetValue(); 
}

我该怎么做呢?

使用泛型:

public interface IClass<T> where T : BaseClass
{
   T GetValue();
}
class Child: BaseClass, IClass<Child>
{
   Child GetValue(); 
}

那不是那么容易。 您期望它起作用的方式不是因为任何实现IClassIClass必须从接口完全实现该方法(如果您有IClass的实例,您怎么知道GetValue()返回的静态类型是Child?有一些使用泛型的解决方法,但使用起来可能不太好,例如

 public T GetValue<T>();

您可以在其中精确指定要返回的类型。 但是,如果与虚拟重载结合使用,这可能会变得非常难看。 另一种选择是创建一个新的实现:

class Child: BaseClass, IClass
{
    BaseClass IClass.GetValue(); 
    new Child GetValue();
}

这样,你得到一个BaseClass ,如果静态类型的调用的对象是IClassChild ,如果它是一个静态的Child

记住

IClass a = new Child();
Child b = a.GetValue(); // Error: Cannot convert BaseClass to Child

因为IClass.GetValue()的静态返回类型是BaseClass,所以它将永远无法工作。

暂无
暂无

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

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