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

问题描述 投票:0回答:1

这是编写此代码的更好方法吗?这种方式看起来很复杂。我想根据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();
c# .net anonymous-function func
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.