如果我想要一个泛型方法有很多泛型类型,例如最多 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?
}
最佳答案
如果您查看 Action<T1, T2, ....>
的文档看来您需要单独实现所有重载。
这是 reference source它的。如您所见,它已按照您的示例完成。
关于为什么 params
的更详细的答案等效项不存在可以通过 Jon Skeet here 找到.
它指出:
“就 CLR 而言,从根本上说 Func<T>
和 Func<T1, T2>
是完全不相关的类型,没有什么能像 params 那样指定多个类型参数。”
关于c# - 具有多种类型的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52054885/