【发布时间】:2011-09-28 16:43:18
【问题描述】:
我有一个泛型类组的非泛型接口。我有一个方法,它使用协方差在派生自非泛型类组的抽象实现的类中返回强类型实例。
所以基本上有了这个设置,我有很多课程,例如ActualThing1 和 ActualThing2。这些类有一个Clone 方法,该方法返回自身的强类型克隆。
以下是我如何构建接口和类。我不确定这是否正确。
通常,我根本不会有非泛型抽象类。但这是必要的,因为在某些情况下我必须对子对象做一些事情,引用一个内部方法_SomethingNeededInternally。这不能使用接口完成,因为它是受保护的,也不能从泛型类内部完成,因为子类可能不是同一类型(它们可能是从接口派生的不同类型)。因此,非泛型基类Something。
这可行,但对我来说不太有意义的是我的抽象 Something 类中需要的 ISomething.Clone 的显式实现。它必须在那里,但不应该实现,因为我希望将该实现推迟到派生自它的泛型类。但是没有 abstract ISomething ISomething.Clone() 这样的语法。
但是那个代码(抛出异常的地方)永远无法执行,可以吗,因为我没有这个对象的任何非泛型实现?
我想我想知道是否有更好的方法来做到这一点,因为它似乎不对。也就是说,我依赖于这样一个事实,即永远不会从接口创建非泛型类,这闻起来很有趣。
public interface ISomething
{
// ...
ISomething Clone();
}
public abstract class Something: ISomething
{
ISomething ISomething.Clone()
{
throw new Exception("This should not be happening");
}
protected int _SomethingNeededInternally;
}
public abstract class Something<T>: Something, ISomething where T: ISomething, new()
{
public abstract T Clone();
ISomething ISomething.Clone()
{
return Clone();
}
}
public interface IActualThing {} // this could be any interface
public class ActualThing: Something<ActualThing>, IActualThing
{
public override ActualThing Clone()
{
return new ActualThing(); // do cloning here
}
}
【问题讨论】:
-
你的 ISomething 接口是故意内部的?
-
不,这不应该是公开的。已编辑。
-
如果代码实际上是可编译的,它会更容易阅读。建议的编辑(待批准)。答案中重复出现编译错误,因此难以评估。
-
@Roman Boiko - 这是伪代码,因此不应该是完整的,但只是为了好玩,我尝试按原样编译它。它对我来说编译得很好,我没有看到任何语法错误。你觉得哪里不对?
-
哦,我看到你编辑了,没关系。
标签: c# generics covariance