开发者

Assign a variable the result of dynamic function call in C#

In JavaScript I can a开发者_如何学运维ssign a value to a variable by dynamically creating a function. Such as

var name = (function () { name="bob"; return name; }());

I'm fairly certain that with C# 4.0 the same type of thing is possible. Could someone show me the syntax of how the same line above would look in C#?

Also, if you could jog my memory on what the proper term for creating this type of dynamic function is, it would be much appreciated!

Thanks for your help!

PS: It's likely this question has been asked before, but since I was unclear on the nomenclature I may have missed finding it. If that's the case, I apologize!


You can use anonymous methods:

Func<string> anonymousFunction = () => { string name = "bob"; return name; };
string myName = anonymousFunction();

The syntax on the first line is a lambda, which is the C#3.0 and above way of declaring anonymous methods. The above function takes no arguments, but there's nothing stopping you from including them as well:

Func<string, string> makeUppercase = x => x.ToUpper();
string upperCase = makeUppercase("lowercase");

Note that since there is only one parameter, you can elide the brackets around it. As well, since the entire method is a single return statement, you can elide both the brace brackets as well as the return statement itself.

This type of lambda is very common when using the LINQ extension methods, since many of them require a single-argument method that returns a value:

var numbers = new List<int>() { 1, 2, 3, 4 };
var divisibleByTwo = numbers.Where(num => num % 2 == 0);

To answer your actual question, that syntax is not valid in C#. If you try this:

string output = (x => x.ToUpper())("lowercase");

You'll get an error message saying "Method name expected." You have to assign the anonymous method to a delegate first.


Generally what you want to look into are Func/Actions:

http://msdn.microsoft.com/en-us/library/bb549151.aspx

http://msdn.microsoft.com/en-us/library/018hxwa8.aspx

And for that matter, lambda expressions:

http://msdn.microsoft.com/en-us/library/bb397687.aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜