你可以声明一个可变长度的泛型类型声明吗? [英] Can you declare a variable length Generics type declaration?
问题描述
我有一个重载的实用程序方法,名为 CheckDuration
,其中包含以下功能签名。
private static Action< int> CheckDuration(动作动作)
private static动作< int> CheckDuration< T>(Action T行动,T arg)
基本上 CheckDuration
在控制台上打印多长时间运行一个方法。
现在,我想检查一个方法的持续时间,需要2
所以我必须用下面的方法签名创建另一个重载的 CheckDuration
。
private static Action< int> CheckDuration< T,U>(
Action action,T arg1,U arg2)
有没有办法更好地处理这个问题?
我正在考虑类似于
private static Action< int> CheckDuration< params T>(
Action action,params T arg)
,这显然不起作用。
[UPDATE] 我现在将留下这个问题,看看是否有人提出了一个解决方案
不幸的是,你已经是一样干净,因为它会得到。 C#不支持将
params
用于泛型类型参数,并且支持类似的东西将非常困难。你最初的解决方案是很好的,并且在BCL中类似于 Action
委托的类似委托的精神,它们重载了定义以获取不同数量的参数。 I have an overloaded utility method called CheckDuration
with following function signatures.
private static Action<int> CheckDuration(Action action)
private static Action<int> CheckDuration<T>(Action<T> action, T arg)
Basically CheckDuration
prints on console how long it took to run a method.
Now, I would like to check the duration of a method that takes 2 argument.
So I would have to create another overloaded CheckDuration
with following method signature.
private static Action<int> CheckDuration<T, U>(
Action<T, U> action, T arg1, U arg2)
Is there a way to handle this more gracefully?
I was thinking about something like
private static Action<int> CheckDuration<params T>(
Action<params T> action, params T arg)
, which obviously doesn't work.
[UPDATE] I will leave this question open for now to see if anyone has come up with a work-around for this kind of problem.
Unfortunately what you have already is about as clean as its going to get. C# does not support the use of params
for generic type parameters and supporting something like that would be very difficult. Your original solution is good and is in the spirit of similiar delegates in the BCL like the Action
delegates which have overloaded definitions to take different numbers of arguments.
这篇关于你可以声明一个可变长度的泛型类型声明吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!