开发者

Why I cannot use the anonymous method like that?

开发者 https://www.devze.com 2023-01-08 16:53 出处:网络
Why can\'t I have this? I mean it would spare a delegate declaration: int X=delegate int(){...}; I know it can be done 开发者_StackOverflow中文版this way:

Why can't I have this? I mean it would spare a delegate declaration:

int X=delegate int(){...};

I know it can be done 开发者_StackOverflow中文版this way:

delegate int IntDelegate();
...
IntDelegate del=delegate(){return 25;};
int X=del();


A delegate is not an int.

If you use .Net 3.5 or newer you can use the built in Func instead of using a custom (Func also have generic types if you need arguments like Func which tages a string and return an int):

Func<int> X = delegate() { return 255; };

or with lambda expressions:

Func<int> X = () => 255;

Unfortunately, you can't say:

var X2 = () => 255;

in C# but you can do something similar in functional languages ex F#. Instead you would say the following in C#:

var X2 = new Func<int>(() => 255);


Tomas,

would this work for you:

    delegate int IntDelegate();
    // other stuff...
    IntDelegate _del = () => 25;

jim

[edit] - oops, just realised, the question was re making it a one liner!! - i'll have a think


Because in the first example, you're trying to assign a delegate type into an int, rather than the output of a delegate into an int. A delegate is a type that stores a function, which just so happens to return a value that you're interested in.


Is there really a need for creating a delegate, executing it, and returning the value? Why not just execute the code directly?

int x = new Func<int,int>(num => num*num) (3);

would return 9, but so would:

int x = 3*3;
0

精彩评论

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