我有一个通用类组的非通用接口(interface)。我有一个方法,它使用协方差返回派生自非泛型类组的抽象实现的类中的强类型实例。
所以基本上通过这个设置,我有很多类(class),例如ActualThing1
和 ActualThing2
。这些类有一个 Clone
方法,该方法返回它们自身的强类型克隆。
下面是我构建接口(interface)和类的方式。我不确定这是否正确。
通常,我根本不会有非泛型抽象类。但这是必要的,因为在某些情况下,我必须对子对象执行某些操作,引用内部方法_SomethingNeededInternally
。这不能使用接口(interface)来完成,因为它是 protected ,也不能从泛型类内部完成,因为子类可能不是同一类型(它们可能是从接口(interface)派生的不同类型)。因此,非泛型基类 Something
。
这可行,但对我来说不太有意义的是我的抽象 Something
类中需要的 ISomething.Clone
的显式实现。它必须在那里,但不应该被实现,因为我希望该实现推迟到从它派生的泛型类。但是没有像 abstract ISomething ISomething.Clone()
这样的语法。
但是该代码(抛出异常的地方)永远无法执行,不是吗,因为我没有该对象的任何非通用实现?
我想我想知道是否有更好的方法来做到这一点,因为这似乎不对。也就是说,我依赖于这样一个事实:非泛型类永远不会从接口(interface)创建,这听起来很有趣。
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
}
}
最佳答案
添加所需的方法作为 Clone 的实现对您有用吗? (我仍然不确定你的整个问题是什么,这只会解决抽象显式接口(interface)实现的语法。)
public abstract class Something: ISomething
{
ISomething ISomething.Clone()
{
return CloneYouMust();
}
abstract ISomething CloneYouMust();
}
关于c# - 使用泛型实现显式接口(interface)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7586629/