2012-02-03 3 views
1

우리는 인터셉터 객체를 사용하여 NHibernate에게 엔티티를 저장하기 전에 몇 가지 일반적인 작업을 수행하도록 지시하는 프로젝트를 가지고 있습니다.이 인터셉터는 할일이 하나 있습니다. 이제이 인터셉터에 추가해야 할 또 다른 작업이 있습니다. (NHibernate 여러 인터셉터를 지원하지 않습니다)하지만 난 대신 복잡한이 인터셉터가 나는 모든이 같은 interceptors.something 등록 된 관리하게 구성 패턴을 사용하고자 만들고 싶어하지 않습니다NHibernate IInterceptor composition

public bool Onload(object entity,object id,object[] state,string propertyNames,IType[] types_ 
{ 
var result=false; 
foreach(var interceptor in _registeredInterceptors) 
result=result || interceptor.OnLoad(entity,id,state,propertyNames,types); 
return result; 
} 

public bool OnFlushDirty(object entity,object id,object[] state,string propertyNames,IType[] types_ 
{ 
var result=false; 
foreach(var interceptor in _registeredInterceptors) 
result=result || interceptor.OnFlushDirty(entity,id,state,propertyNames,types); 
return result; 
} 

이 코드 I보고를 나를 반복하지 못하게하는 더 좋은 방법이있을 수 있음을 깨달았습니다. 질문은 람다 식과 yield 키워드를 사용하여이 코드를보다 간단하고 추상적으로 만들 수 있습니까?

+0

나는 클로저를 사용하고 싶기 때문에 람다 식을 언급 했으므로 각 메서드 집합에 대해 개별 대리자를 만들 필요가 없습니다. – Beatles1692

답변

2

과 같이 볼 수 있었다 그 일을하는 한 가지 방법 :

public bool Execute(IList<IInterceptor> interceptors, Func<IInterceptor, bool> func) 
{ 
    bool result = false; 
    foreach (IInterceptor interceptor in interceptors) 
    { 
     result = result || func(interceptor); 
    } 

    return result; 
} 

그리고 부모 요격에

: 당신이 원하는 경우

public bool Onload(object entity, object id, object[] state, string propertyNames, IType[] types_ 
{ 
    return Execute(_registeredInterceptors, x => x.OnLoad(entity, id, state, propertyNames, types); 
} 

public bool OnFlushDirty(object entity, object id, object[] state, string propertyNames, IType[] types_ 
{ 
    return Execute(_registeredInterceptors, x => x.OnFlushDirty(entity, id, state, propertyNames, types); 
} 

업데이트하는

결과 유형은 일반적인 될 수 다음과 같이 할 수 있습니다.

public static T Execute<T>(IList<IInterceptor> interceptors, Func<IInterceptor, T> func) 
{ 
    T result = default(T); 
    foreach (IInterceptor interceptor in interceptors) 
    { 
     // your logic based on type T 
    } 

    return T; 
} 

Type inference 때문에 일반 버전의 실행이 정확히 bool과 같습니다.

당신이 염두에 두었던 것이 이것입니까?

+0

글쎄 일종의 :)하지만 여전히 각 반환 값 (개체, 무효, int)에 대해 별도의 실행 메서드를 작성해야합니다. 나는 모든 시나리오에 대한 일반적인 방법을 만들 수 있도록 어쨌든 거기에 생각입니다. – Beatles1692

+0

내 대답을 업데이 트했습니다,이 * generic * 버전의 유일한 문제점은 구현하려는 모든 메소드에 대한 일반화를 찾아야한다는 것입니다. 그러나 이미 그 중 하나를 알아 냈을 것입니다. – MonkeyCoder

+0

글쎄, 하지만 내가 어떻게 bool.I 시도 (typeof (T) == typeof (bool)) 결과 = (bool) 결과를 일반적인 유형을 캐스팅 할 수 실현하지 못했습니다 | | (bool) func; 하지만 컴파일러 오류가 어떤 단서를 얻고 있습니까? – Beatles1692

관련 문제