繁体   English   中英

C# generic - 我可以在其中引用接口的实现吗?

[英]C# generic - Can I refer to an implement of an interface inside it?

我有一些这样的代码:

public interface Base<TImpl, T1> 
  where TImpl : Base<TImpl, T1> 
{
  public T1 Build(TImpl arg);
}

public class Impl1 : Base<Impl1, int>
{
  public int Value { get; set; }

  public int Build(Impl1 arg)
  {
     return arg.Value;
  }
}

public class Impl2 : Base<Impl2, string>
{
  public string Value { get; set; }

  public string Build(Impl2 arg)
  {
     return arg.Value;
  }
}

TImpl通用参数对我来说似乎很丑陋。 我是否有机会安全地删除TImpl部分,或删除T1, T2...并且可以编写类似public TImpl.C1 Method(TImpl arg); ?

这将是Curiously recurring template pattern 的一个例子。 当只有一个实现类时,这没有多大意义。

这种模式的重点是确保Impl.Method的参数也是Impl 在提供相同级别的类型安全性的同时,没有任何简单的方法可以避免这种模式。

Eric Lippert 是 C# 背后的架构师之一,他在一篇关于这个主题文章中指出,虽然该模式有一些潜在的用途,但它也有问题(感谢 Matthew Watson 指出)。 并得出结论:

我的建议是,在用 C# 实现这种奇怪的模式之前,要仔细考虑; 给客户带来的好处真的超过了你给代码维护者带来的精神负担所带来的成本吗?

您也可以始终忽略类型安全,而只是获取和返回对象,但我不建议这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM