c# - 实现通用方法

标签 c# .net generics c#-4.0 interface

我用一种方法创建了一个接口(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/

相关文章:

c# - LINQ 嵌套数组和三元运算符。不支持嵌套查询。操作 1 ='Case' 操作 2 ='Collect'

c# - 如何使用 TreeView.Tag = object?

javascript - 如何将js中的数组转换为C#中的数组?

java - 从其类返回泛型类型的实例

c# - 使用两个相似的 Collection View 单元格,从而避免代码重复

c# - 在代码隐藏 C# 中访问 html 文本框和标签数据

.net - 输入键触发错误的提交按钮

c++ - 错误C++: ‘const_iterator’没有命名类型;

c# - 通用/类型安全的 ICommand 实现?

c# - 如何使用代码隐藏创建 StackPanel -> Border -> Background