使用“参数” C#中通用参数的关键字 [英] Using the "params" keyword for generic parameters in C#

查看:68
本文介绍了使用“参数” C#中通用参数的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了美丽的 Func< T1,T2,T3,T4, T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,TResult> 委托给C#.NET 4.5。我假设16是一个任意停止的地方(哪些方法有16个以上的参数?),但它让我想到:在C#中可以指定一个泛型类型可以有任意数量的类型参数吗?以类似的方式,方法的params关键字允许任意数量的方法参数。像这样:

  public class MyInfiniteGenericType< params T []> {...} 

在类内部,您可以通过枚举来访问类型参数,或者使用 T [index] ,方法与 params 允许的方式一样。



我个人从来没有使用过这个功能,但Func代表将是一个完美的使用它的地方。不需要16种不同类型的Func!

所以我的问题是,这可以以任何方式在C#中完成,而如果不是这样的一个愚蠢的想法

解决方案


有可能在C#中指定泛型type可以有任意数量的类型参数?


不,C#没有这样的恐惧。



基本上 Func< T> Func< T1,T2> 就CLR而言是完全不相关的类型,并且没有任何东西像 params 来指定多个类型参数。



至于它的效用:我可以看到它可能有用的情况,但我怀疑它们非常罕见,意味着该功能不会跨越收益/成本阈值。 (请注意,它几乎肯定需要CLR更改。)


I came across the beautiful Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> delegate in C# .NET 4.5 today. I assume 16 was an arbitrary place to stop (what methods have more than 16 parameters?) but it got me thinking: is it possible in C# to specify that a generic type can have any number of type arguments? in a similar way that the params keyword for methods allows for any number of arguments for a method. Something like this:

public class MyInfiniteGenericType<params T[]> { ... }

where inside the class you could then access the type arguments by enumerating through them or using T[index] in the same way that params allows within methods.

I've never had a use for this personally, but the Func delegate would be a perfect place to use it. There would be no need for 16 different types of Func!

So my question is, can this be done in any way in C#, and if not is this a silly idea?

解决方案

is it possible in C# to specify that a generic type can have any number of type arguments?

No, C# doesn't have anything like that I'm afraid.

Fundamentally Func<T> and Func<T1, T2> are entirely unrelated types as far as the CLR is concerned, and there's nothing like params to specify multiple type arguments.

As for its utility: I can see cases where it could be useful, but I suspect they're rare enough to mean the feature doesn't cross the "benefit/cost" threshold. (Note that it would almost certainly require CLR changes too.)

这篇关于使用“参数” C#中通用参数的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆