2010-04-16 61 views

回答

0

我不认为有通过Func键声明函数......虽然你可以做一个办法:

public static bool MyMethod(int someid, params string[] types) {...} 
public static Func < int,params string[], bool > MyFunc = MyMethod; 
3

简短的回答,你不能,如果你真的想保留params功能。

否则,你可以勉强接受:

Func<int, string[], bool> MyMethod = (id, types) => { ... } 

bool result = MyMethod(id, types); 
0

我想你想函数求声明这样:

public static Func<int, string[], bool> MyMethod = ??? 
8

params关键字编译与ParamArray一个普通的参数。您无法将属性应用于通用参数,因此您的问题是不可能的。

请注意,您仍然可以使用常规(非params)委托:

Func<int, string[], bool> MyMethodDelegate = MyMethod; 

为了使用params关键字与代表,你需要使自己的委托类型:

public delegate bool MyMethodDelegate(int someid, params string[] types); 

你甚至可以使它通用:

public delegate TResult ParamsFunc<T1, T2, TResult>(T1 arg1, params T2[] arg2); 
+0

OK,我把它收回,是可以做到的,很好的解决方案:) – Benjol 2010-04-17 11:35:43

0

这样的辅助方法如何?

public static TResult InvokeWithParams<T, TResult> 
(this Func<T[], TResult> func, params T[] args) { 
    return func(args); 
} 

public static TResult InvokeWithParams<T1, T2, TResult> 
(this Func<T1, T2[], TResult> func, T1 arg1, params T2[] args2) { 
    return func(arg1, args2); 
} 

很明显,你可以为Func额外的通用重载(以及Action,对于这个问题)实现这一点。

用法:

void TestInvokeWithParams() { 
    Func<string[], bool> f = WriteLines; 

    int result1 = f.InvokeWithParams("abc", "def", "ghi"); // returns 3 
    int result2 = f.InvokeWithParams(null); // returns 0 
} 

int WriteLines(params string[] lines) { 
    if (lines == null) 
     return 0; 

    foreach (string line in lines) 
     Console.WriteLine(line); 

    return lines.Length; 
} 
相关问题