简体   繁体   English

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

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

I have some code like this:我有一些这样的代码:

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;
  }
}

The TImpl generic argument seems quite ugly to me. TImpl通用参数对我来说似乎很丑陋。 Do I have a chance to safely remove the TImpl part, or remove T1, T2... and can write something like public TImpl.C1 Method(TImpl arg);我是否有机会安全地删除TImpl部分,或删除T1, T2...并且可以编写类似public TImpl.C1 Method(TImpl arg); ? ?

This would be an example of Curiously recurring template pattern .这将是Curiously recurring template pattern 的一个例子。 It does not make much sense when there is only one implementing class.当只有一个实现类时,这没有多大意义。

The point of this pattern is to make sure that the argument to Impl.Method is also Impl .这种模式的重点是确保Impl.Method的参数也是Impl There would not be any simple way to avoid this pattern while supplying the same level of type-safety.在提供相同级别的类型安全性的同时,没有任何简单的方法可以避免这种模式。

Eric Lippert, one of the architects behind C#, has an article on the subject where he points out that while the pattern have some potential uses, it also have problems (thanks to Matthew Watson for pointing it out). Eric Lippert 是 C# 背后的架构师之一,他在一篇关于这个主题文章中指出,虽然该模式有一些潜在的用途,但它也有问题(感谢 Matthew Watson 指出)。 And conclude with:并得出结论:

My advice is to think very hard before you implement this sort of curious pattern in C#;我的建议是,在用 C# 实现这种奇怪的模式之前,要仔细考虑; do the benefits to the customer really outweigh the costs associated with the mental burden you're placing on the code maintainers?给客户带来的好处真的超过了你给代码维护者带来的精神负担所带来的成本吗?

You could also always ignore type-safety and just take and return objects, but I would not recommend it.您也可以始终忽略类型安全,而只是获取和返回对象,但我不建议这样做。

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

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