Bar*_*yży 0 .net c# anonymous-function func
这是编写此代码的更好方法吗?这种方式看起来很复杂.我想example根据需要分配值anotherVariable.
var example = new Func<DateTime>((() =>
{
switch (anotherVariable)
{
case "Jesus birth": return new DateTime(0, 12, 24);
case "Second condition": return new DateTime(2017, 23, 11);
// etc
default: return DateTime.Now;
}
})).Invoke();
Run Code Online (Sandbox Code Playgroud)
您不必将代码包装在委托中 - 只要每个case(包括default)分配显式类型的变量,此代码都将正常工作:
DateTime example;
switch (anotherVariable)
{
case "Jesus birth": example = new DateTime(0, 12, 24); break;
case "Second condition": example = new DateTime(2017, 23, 11); break;
// etc
default: example = DateTime.Now; break;
}
Run Code Online (Sandbox Code Playgroud)
如果您坚持使用委托,则无需致电Invoke,因为您知道委托的类型.您可以使用简单的调用语法:
var example= (() => {
switch (anotherVariable) {
case "Jesus birth": return new DateTime(0,12,24); break;
case "Second condition": return new DateTime(2017,23,11); break;
//another cases
default: return DateTime.Now; break;
}
}) ();
// ^^
// Invocation
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |