C# 如何用N个参数定义委托函数
我想知道是否有一种方法可以定义一个参数数目可变的泛型函数。例如,我定义了泛型函数:C# 如何用N个参数定义委托函数,c#,.net,generics,delegates,func,C#,.net,Generics,Delegates,Func,我想知道是否有一种方法可以定义一个参数数目可变的泛型函数。例如,我定义了泛型函数: public T MeasureThis<T>(Func<T> funcToMeasure) { var watch = new Stopwatch(); watch.Start(); T returnVal = funcToMeasure(); watch.Stop(); Console.Writ
public T MeasureThis<T>(Func<T> funcToMeasure)
{
var watch = new Stopwatch();
watch.Start();
T returnVal = funcToMeasure();
watch.Stop();
Console.WriteLine("Time elapsed: {0}", watch.Elapsed);
return returnVal;
}
public T MeasureThis(Func functtomeasure)
{
var watch=新秒表();
watch.Start();
T returnVal=funcToMeasure();
看,停;
WriteLine(“经过的时间:{0}”,watch.appeased);
返回值;
}
而且:
public T MeasureThis<T>(Func<int,int,T> funcToMeasure, int p1, int p2)
{
var watch = new Stopwatch();
watch.Start();
T returnVal = funcToMeasure(p1, p2);
watch.Stop();
Console.WriteLine("Time ellapsed: {0}", watch.Elapsed);
return returnVal;
}
public T MeasureThis(Func functtomeasure,int p1,int p2)
{
var watch=新秒表();
watch.Start();
T returnVal=功能测量(p1,p2);
看,停;
WriteLine(“时间延迟:{0}”,watch.passed);
返回值;
}
我想测量函数需要执行到最后的时间。问题是要测量的函数可以有无、一、二、三。。。。参数。如果我想测量包含10个参数的函数,我应该定义10次相同的函数吗
谢谢 一个简单的技巧是只使用返回类型的最简单的
Func
,而不是将其他类型作为类型参数传递给泛型,而是使用闭包从周围的上下文中捕获它们
例如:
int SomeFunctionWith3Args(int arg1, int arg2, int arg3) { ... }
使用另一个泛型类型X来表示具有许多属性的类
public T MeasureThis<T>(Func<X,T> funcToMeasure, X x) where X : class
{
var watch = new Stopwatch();
watch.Start();
T returnVal = funcToMeasure(x);
watch.Stop();
Console.WriteLine("Time ellapsed: {0}", watch.Elapsed);
return returnVal;
}
public T MeasureThis(Func functtomeasure,X X)其中X:class
{
var watch=新秒表();
watch.Start();
T returnVal=函数测量(x);
看,停;
WriteLine(“时间延迟:{0}”,watch.passed);
返回值;
}
如果您使用的是库存CLR委托(例如,Func
),您的方法将需要匹配委托签名。可以使用可选参数创建方法:
public int Foo( int x , int y = int.MinValue ) { ... }
并将其毫无问题地分配给适当的代表:
Func<int,int,int> delegateX = Foo ;
您可以使用具有默认值的方法,例如:
public TResult Foo<T1,T2,TResult>( T1 p0 , T2 p1 = default(T2) , T2 p2 = default(T2) ) { ... }
public-TResult-Foo(T1-p0,T2-p1=default(T2),T2-p2=default(T2)){…}
应该注意的是,当您有涉及可选参数的方法重载时,会有陷阱:
public int Foo( int x , int y = int.MinValue ) { ... }
Func<int,int,int> delegateX = Foo ;
Func<int,int> delegateY = Foo ;
public TResult Foo<T1,T2,TResult>( T1 p0 , params T2[] p1 ) { ... }
public TResult Foo<T1,T2,TResult( T1 p0 , T2 p1 , T2 p2 , T2 p3 ) { ... }
public TResult Foo<T1,T2,TResult( T1 p0 , T2 p1 , T2 p2 ) { ... }
public TResult Foo<T1,T2,TResult( T1 p0 , T2 p1 ) { ... }
public TResult Foo<T1,T2,TResult>( T1 p0 , T2 p1 ) { ... }
public TResult Foo<T1,T2,TResult>( T1 p0 , T2 p1 , T2 p2 ) { ... }
public TResult Foo<T1,T2,TResult>( T1 p0 , T2 p1 , T2 p2 , T2 p3 ) { ... }
public TResult Foo<T1,T2,TResult>( T1 p0 , params T2[] p1 ) { ... }
public TResult Foo<T1,T2,TResult>( T1 p0 , T2 p1 = default(T2) , T2 p2 = default(T2) ) { ... }