c# - 具有多种类型的通用方法

标签 c# generics methods overloading

如果我想要一个泛型方法有很多泛型类型,例如最多 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/

相关文章:

python - 为什么 destroy() 方法在我的 tkinter 程序中不起作用?

c# - 如何链接2个组合框

c# - 在 EntityFramework 4.1 中如何使用 Moles 从查询数据库中窃取 DbContext?

c# - .NET 4.5.1 与 .NET Core 5

generics - 如何在 Swift 中返回一个序列?

delphi - 泛型:什么是 "CONSTRUCTOR constraint"?

java - 调用方法、参数和参数

java - vector 、点、战舰、2D

c# - App.config 文件中的连接字符串,用于从本地计算机连接到 EC2 SQL Server 2008 R2

generics - 为什么我不能在带有类型参数的特征上添加一揽子实现?