6

是否可以将 Func 委托作为扩展方法?例如,就像您可以创建函数一样

bool isSet(this string x) {return x.Length > 0;}

我希望能够写出类似的东西

Func<string, bool> isSet = (this x => x.Length > 0);

当然,以上在语法上是不正确的。有什么东西吗?如果不是,那是语法或编译的限制吗?

4

3 回答 3

14

简短的回答:不,那不可能。

扩展方法是语法糖,只能在某些情况下定义(静态类中的静态方法)。lambda 函数没有与此等价的功能。

于 2012-06-25T16:30:35.613 回答
7

是否可以将 Func 委托作为扩展方法?

不可以。扩展方法必须在顶级(非嵌套)非泛型静态类中声明为普通静态方法。

看起来您将尝试仅为该方法的范围创建扩展方法 - C# 中没有类似的概念。

于 2012-06-25T16:31:58.723 回答
4

To answer the question in comments on why this is wanted you coudl define the isSet func normally and just use that as a method call which will have the same effect as your extension method but with different syntax.

The syntax difference in use is purely that you'll be passing the string in as a parameter rather than calling it as a method on that string.

A working example:

public void Method()
{
    Func<string, bool> isSet = (x => x.Length > 0);

    List<string> testlist = new List<string>() {"", "fasfas", "","asdalsdkjasdl", "asdasd"};
    foreach (string val in testlist)
    {
        string text = String.Format("Value is {0}, Is Longer than 0 length: {1}", val, isSet(val));
        Console.WriteLine(text);
    }
}

This method defines isSet as you have above (but without the this syntax). It then defines a list of test values and iterates over them generating some output, part of which is just calling isSet(val). Funcs can be used like this quite happily and should do what you want I'd think.

于 2012-06-25T16:51:47.570 回答