C# 4.0 Anonymous Functions
How do I do the following shown in Javascript in C# 4.0:
var output = doSomething(variable, function() {
// Anonymous function code
});
I'm sure I've seen this somewhere 开发者_开发知识库before but I cannot find any examples.
Using a lambda expression (parameterless, therefore empty parentheses), it is very simple:
var output = doSomething(variable, () => {
// Anonymous function code
});
In C# 2.0, the syntax was a bit longer:
SomeType output = doSomething(variable, delegate {
// Anonymous function code
});
You'll want to look in to Lambda Expressions though it's not QUITE like JavaScript because C# works quite a bit differently. You may also want to check out delegates.
Example Code:
namespace Test {
class Tests {
delegate string MyDelegate();
public void Main(string[] args) {
var output = doSomething("test1", () => { return "test2";} );
}
public string doSomething(string test, MyDelegate d) {
return test + d();
}
}
}
var output = (x) => {
// Anonymous function code
};
精彩评论