编写此代码是更好的方法吗?这种方式看起来很复杂。我想根据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();
答案 0 :(得分:6)
您不必将代码包装在委托中 - 只要每个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;
}
如果您坚持使用委托,则无需致电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