我用一种方法创建了一个接口(interface),能够将一个对象的内容复制到另一个相同类型的对象中(实际功能与问题无关)。
public interface IDeepClonable
{
void DeepClone<T>(T other);
}
我在正确实现方面遇到了问题。
我真正想要的是像这样实现它(这是在实现 IDeepClonable 的 ClassA 内部)
public void DeepClone<ClassA>(ClassA other)
{
this.A = other.A;
}
但是这不起作用,因为“其他”对象未被编译器识别为 ClassA 的实例(为什么?)
这也不起作用,因为它给出了“类型参数 T 的约束必须匹配 (...) 接口(interface)方法”。
public void DeepClone<T>(T other) where T : ClassA
{
this.A= other.A;
}
我可以通过更改接口(interface)以接受对象而不是通用约束来解决所有问题,但我希望有一个更优雅的解决方案。
我也可以通过将接口(interface)转换为通用接口(interface)来解决这个问题,但这会迫使我强制转换为该通用接口(interface)。
最佳答案
您正在尝试使用 CRTP .
你需要写
public interface IDeepClonable<out T> where T : IDeepClonable<T>
{
void DeepClone(T other);
}
public class ClassA : IDeepClonable<ClassA> {
void DeepClone(ClassA other) { ... }
}
但是,这意味着任何使用 IDeepClonable
的代码本身都必须变得通用,这最终会变得笨拙。
CLR 类型系统不够丰富,无法满足您的真正需求。
关于c# - 实现通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10485144/