2017-12-23 3 views
0

このコードを書く方が良いですか?この方法はとても複雑に見えます。 anotherVariableに応じてexampleの値を割り当てたいとします。C言語で匿名メソッドを呼び出すよりクリーナーな方法#

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

答えて

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 
+0

それはそれです。ありがとう! –

関連する問題