C# 在接口中使用基类
我有一个基本类:C# 在接口中使用基类,c#,class,interface,C#,Class,Interface,我有一个基本类: class BaseClass{ } public interface IClass { BaseClass GetValue(); } 我想实现使用基类的接口: class BaseClass{ } public interface IClass { BaseClass GetValue(); } 然后创建实现此接口的子类,但在方法中返回了自己的类类型: class Child: BaseClass, IClass { Child GetValue(
class BaseClass{ }
public interface IClass
{
BaseClass GetValue();
}
我想实现使用基类的接口:
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();
}
公共接口类,其中T:BaseClass
{
T GetValue();
}
类子类:基类,IClass
{
子GetValue();
}
使用泛型:
public interface IClass<T> where T : BaseClass
{
T GetValue();
}
class Child: BaseClass, IClass<Child>
{
Child GetValue();
}
公共接口类,其中T:BaseClass
{
T GetValue();
}
类子类:基类,IClass
{
子GetValue();
}
这可不容易。您期望它工作的方式并不是这样,因为任何实现IClass
的类都必须从接口精确地实现该方法(如果您有一个IClass实例,您怎么知道GetValue()返回的静态类型是Child呢?有一些解决方法使用泛型,但它们可能不太好用,例如
public T GetValue<T>();
这样,如果调用中对象的静态类型是IClass
,则得到BaseClass
,如果调用中对象的静态类型是Child
,则得到Child
记得吗
IClass a = new Child();
Child b = a.GetValue(); // Error: Cannot convert BaseClass to Child
将永远不会工作,因为IClass.GetValue()的静态返回类型是基类。这并不容易。您期望它工作的方式并不容易,因为任何实现
IClass
的类都必须从接口准确地实现该方法(如果您有一个IClass实例,您怎么知道GetValue()返回的静态类型是Child呢?有一些使用泛型的变通方法,但它们可能不太好用,例如
public T GetValue<T>();
这样,如果调用中对象的静态类型是IClass
,则得到BaseClass
,如果调用中对象的静态类型是Child
,则得到Child
记得吗
IClass a = new Child();
Child b = a.GetValue(); // Error: Cannot convert BaseClass to Child
永远不会工作,因为IClass.GetValue()的静态返回类型是基类