【发布时间】:2019-02-02 21:52:01
【问题描述】:
如果我想要一个泛型方法有很多泛型类型,例如最多 16 个。
我必须重载该方法 16 次还是有更聪明的方法来做到这一点?
public interface IMyInterface { }
public class MyClass {
public void MyMethod<T1>() where T1 : IMyInterface { }
public void MyMethod<T1, T2>() where T1 : IMyInterface where T2 : IMyInterface { }
public void MyMethod<T1, T2, T3>() where T1 : IMyInterface where T2 : IMyInterface
where T3 : IMyInterface { }
public void MyMethod<T1, T2, T3, T4>() where T1 : IMyInterface where T2 : IMyInterface
where T3 : IMyInterface where T4 : IMyInterface { }
// All the way to T16...
// Is there any smarter way of doing this
// instead of having to write it 16 times?
}
【问题讨论】:
-
你的方法没有实现吗?
-
为了简单起见,我没有包含任何实现。而且我认为实施没有任何重要性。
-
但是你的实现肯定会因每种方法而不同,所以你必须以一种或另一种方式编写它,不是吗?
-
如果你问这个问题,没有办法概括泛型,所以你必须手动或使用 T4 模板来自动化无聊的过程,但最终结果仍然是多个重载,不同数量的仿制药。您可以在此处看到如何自动化的示例:blog.dreasgrech.com/2013/04/…
-
如果所有不同的泛型参数都实现同一个接口,哪里需要区分?
标签: c# generics methods overloading