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

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

问题描述

我遇到了漂亮的Func 委托在今天的 C# .NET 4.5 中.我认为 16 是一个可以停止的任意位置(哪些方法有超过 16 个参数?)但它让我思考:是否可以在 C# 中指定泛型类型可以有任意数量的类型参数? 以类似的方式,方法的 params 关键字允许方法的任意数量的参数.像这样:

public class MyInfiniteGenericType{ ... }

然后您可以在类中的哪个位置通过枚举或使用 T[index] 来访问类型参数,就像 params 在方法中允许的那样.>

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

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

解决方案

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

不,我担心 C# 没有类似的东西.

从根本上说,FuncFunc 就 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天全站免登陆