比在C#中调用匿名方法的清洁方法



编写此代码的方法更好吗?这样看起来很复杂。我想根据anotherVariable分配example值。

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();

您不必将代码包装在代表中 - 只要每个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

最新更新