使用“参数” C#中通用参数的关键字

编程入门 行业动态 更新时间:2024-10-20 00:31:23
本文介绍了使用“参数” 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#中通用参数的关键字

本文发布于:2023-11-11 06:02:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   关键字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!