C# Variable = new function () {};

Within C# is it possible to create a new function on the fly to define a variable?

I know that

string getResult() {
    if (a)
        return "a";
    return "b";
}
String result = getResult();

is possible, but I'm looking for something like

String result = new string getResult() {
    if (a)
        return "a";
    return "b";
}

Is this possible? If so, would someone demonstrate?

EDIT It is possible

Edit: Final - Solution

This is the end result of what I barbarically hacked together

Func<string> getResult = () =>
{
    switch (SC.Status)
    {
        case ServiceControllerStatus.Running:
            return "Running";
        case ServiceControllerStatus.Stopped:
            return "Stopped";
        case ServiceControllerStatus.Paused:
            return "Paused";
        case ServiceControllerStatus.StopPending:
            return "Stopping";
        case ServiceControllerStatus.StartPending:
            return "Starting";
        default:
            return "Status Changing";
    }
};

TrayIcon.Text = "Service Status - " + getResult();

One way to define such a function:

Func<bool, string> getResult = ( a ) => {
    if (a)
        return "a";
    return "b";
}

You can then invoke: string foo = getResult( true ); . As a delegate, it can be stored/passed and invoked when needed.

Example:

string Foo( Func<bool, string> resultGetter ){
    return resultGetter( false );
}

You can also close around variables within scope:

bool a = true;

Func<string> getResult = () => {
    if (a)
        return "a";
    return "b";
}

string result = getResult();

你想使用内联if语句。

string result = a ? "a" : "b";

If you really want inline you can make an extension method for type String :

static class StringExtensions {
    public static string ExecuteFunc(
            this string str, 
            Func<string, string> func
        ) {
        return func(str);
    }
}

And then, when you want to use it, you do so like so:

string str = "foo";

string result = str.ExecuteFunc( s => {
        switch(s){
            case "a":
                return "A";
            default:
                return "B";
        }
    }
);
链接地址: http://www.djcxy.com/p/51092.html

上一篇: MVC3将多个pdf作为zip文件返回

下一篇: C#Variable = new function(){};