2017-12-23 35 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
당신은 대리인에 코드를 포장하지 않아도

-의 default을 포함, 모든 case만큼 명시 적으로 유형 변수를 지정,이 코드는 제대로 작동합니다

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

해당 사항이 있습니다. 감사! –