2012-07-20 4 views
1

나는 다음을 수행하려고 ...체인 IF 조건 및 첫 번째 조건 실행. C#에서

MyObject.If(x => x.ID == 10, new MyAction("ID10")).If(x => x.Value < 20, new MyAction("Value20")).DoSomethingWithMyAction(); 

MyObject를 내가 확인해야 할 몇 가지 속성을 가진 객체입니다

DoSomethingWithMyAction은()와 함께 무언가를 시켜라 확장 기능입니다 실패한 첫 번째 조건의 MyAction.

뭔가처럼 될 수 있다면 :

public static If<T>(this T myobject, Func<T, Boolean> predicate, MyAction action) where T : MyObject { 

    if (predicate(myobject) 
    // Return ??? >> Move to Next If 
    else 
    // Return action 

} // If 

그런 다음 DoSomethingWithMyAction (가) 단순히 시켜라 확장 될 것이다.

내 문제는 다음과 같습니다. 1 - IFs 연결 방법; 2 - DoSomethingWithMyAction()을 만드는 방법은 첫 번째 IF의 MyAction을 사용하여 실패합니다. 내가 질문을 오해 것, 그리고 지금 내 코드를 다시 방문 할 시간이 없어 :

는 미구엘에게,

+1

당신이하려는 것은 관용적이지 않습니다. 그것은 유지할 수없는 것을 경계하고 있습니다. if/else 블록은 이보다 훨씬 쉽게 유지 보수 될 것입니다. – 48klocs

답변

2

편집을 주셔서 감사합니다. 하지만 뭔가은 다음과 같습니다.

아마도 체인 자체를 나타내는 일종의 유형을 구성해야합니다. 뭔가 같은 : 다음

public class ChainedExecution<T> 
{ 
    private readonly T target; 
    private readonly ChainedExecution<T> previous; 
    private readonly Func<T, bool> predicate; 
    private readonly Action<T> action; 

    private ChainedExecution(T target, ChainedExecution<T> previous, 
          Func<T, bool> predicate, Action<T> action) 
    { 
     this.target = target; 
     this.previous = previous; 
     this.predicate = predicate; 
     this.action = action; 
    } 

    public ChainedExecution<T> Or(Func<T, bool> newPredicate, Action<T> newAction) 
    { 
     return new ChainedExecution<T>(target, this, newPredicate, newAction); 
    } 

    public bool Execute() 
    { 
     if (previous != null && previous.Execute()) 
     { 
      // An earlier action has handled it. 
      return true; 
     } 

     if (predicate(target)) 
     { 
      action(target); 
      return true; 
     } 
     return false; 
    } 

    public static ChainedExecution<T> Start(T target, Func<T, bool> predicate, 
              Action<T> action) 
    { 
     return new ChainedExecution<T>(target, null, predicate, action); 
    } 
} 

:

public static class ChainedExecution 
{ 
    public static ChainedExecution<T> If<T>(this T target, 
              Func<T, bool> predicate, 
              Action<T> action) 
    { 
     return ChainedExecution<T>.Start(target, predicate, action); 
    } 
} 

그리고로 사용 : 당신은 MyActionAction<T>을 변경해야하고, Execute 반환 "값을 만들 수 있습니다

foo.If(x => x.Value < 20, x => Console.WriteLine("Bang! Too low")) 
    .Or(x => x.Name == null, x => Console.WriteLine("Null name")) 
    .Execute(); 

"실패한 술어에서"또는 그런 식으로 ... 어쨌든, 그것은 일반적인 요지입니다.