2010-04-16 47 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; 
} 
相關問題