比c#中的Invoke匿名方法更清洁

时间:2017-12-23 21:53:37

标签: c# .net 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();

1 个答案:

答案 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