开发者

How can I take an existing function and write it using Func<..> in C#?

开发者 https://www.devze.com 2022-12-27 07:30 出处:网络
I wrote this code: public static bool MyMethod(int someid, params string[] types) {...} 开发者_如何转开发

I wrote this code:

public static bool MyMethod(int someid, params string[] types)
{...}
开发者_如何转开发

How could I write that using Func?

public static Func < int, ?params?, bool > MyMethod = ???


The params keyword is compiled to an ordinary parameter with the ParamArray. You cannot apply an attribute to a generic parameter, so your question is impossible.

Note that you could still use a regular (non-params) delegate:

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

In order to use the params keyword with a delegate, you'll need to make your own delegate type:

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

You could even make it generic:

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


Short answer, you can't, if you really want to preserve the params functionality.

Otherwise, you could settle for:

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

bool result = MyMethod(id, types);


i'm afraid you couldn't do that.

http://msdn.microsoft.com/en-us/library/w5zay9db%28VS.71%29.aspx


I don't think there's a way to declare functions through Func... although you can just do:

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


I think you want a Func declaration as such:

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


How about some helper methods like these?

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);
}

Obviously, you could implement this for additional generic overloads of Func (as well as Action, for that matter).

Usage:

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消