2011-07-05 2 views
8

우리는 IoC를 사용 중이며 로깅을 공개했습니다. Common.Logging을 사용 중이고 Common.Logging.FormatMessageHandler과 일치하는 대리인을 작성했지만 해당 대리인의 버전을 Common.Logging api가 예상하는 버전으로 변환하는 방법을 모르겠습니다.하나의 대리자를 다른 대리자로 변환하십시오. 가짜 캐스트

이 질문은 유사하지만 구현 된 유형을 호출 할 알려진 유형으로 변환하는 방법을 이해하지 못합니다. 여기

public delegate string FormatMessageHandler(string format, params object[] args) 


이 Common.Logging의이다 :

public delegate string FormatMessageHandler(string format, params object[] args) 

같은 이름 (즉 문제이다) 및 매개 변수의 같은 수의 Dynamically casting one type of delegate to another

여기 내 대리인이 서명입니다. 둘 다 컴파일 타임에 알려지기 때문에 명백한 것이어야하지만 나는 그것을 보지 않을 것이다.

답변

7

정확히 동일한 경우 Common.Logging의 위임을 처음 사용하지 않는 이유는 무엇입니까?
그러나, 문제에 대한 solition 동적 캐스트 당신이 언급 한 질문에 링크 된 문서에 설명 사용하거나, 또는 당신이 이런 식으로 작업을 수행합니다

YourNamespace.FormatMessageHandler yourHandler = ...; 
Common.Logging.FormatMessageHandler handler = (f, a) => yourHandler(f, a); 

UPDATE :
을에 따라 당신이 그런 걸 원하는 논평 :

public void Error(Action<Your.FormatMessageHandler> formatMessageCallback) 
{ 
    _logger.Error(h => formatMessageCallback((f, a) => h(f, a))); 
} 

이 제공된 조치를 호출 유형 Common.Logging.FormatMessageHandlerh 하나 개의 매개 변수를 사용하여 새로운 액션을 만들 것이다 formatMessageCallback의 새 대리자 Your.FormatMessageHandlerfa의 두 매개 변수를 허용합니다. 이 새 대리자는 두 개의 제공된 매개 변수를 사용하여 h을 차례로 호출합니다.

+0

을 기본적으로 동일하게 동작 대단한 내가 작업 을 사용하려고 할 때까지 작동합니다. 액션으로 어떻게 할 수 있습니까? 내 메소드 서명 : 공공 무효 오류 (액션 formatMessageCallback) 그리고 호출하는 마지막 방법은 다음과 같습니다 무효 Common.Logging.Error (액션 formatMessageCallback); –

+0

장래에 다른 로깅 프레임 워크를 사용하기로 결정한 경우 Common.Logging 대리자 또는 API를 노출하지 않을 것입니다. 그런 일이 발생하면 "모든"작업은 앞서 정의한 로깅 인터페이스를 구현하고 호출을 새로운 로깅 프레임 워크로 래핑하는 코드를 작성하는 것입니다. –

+0

@David : 로거의 위임자를 사용하지 않은 이유는 유효합니다. 설명해 주셔서 감사합니다. 첫 번째 의견에 대한 해결책은 업데이트를 참조하십시오. –

1

수동으로 수행 할 수 있지만 전환시 반영되는 비용만큼 비쌉니다. 대리자가 변환되면 그것을 설명 당신의 ...

internal class Program 
{ 
    //An example delegate target 
    static void Click(object o, EventArgs e) { } 

    //A simple test method 
    static void Main(string[] args) 
    { 
     EventHandler onclick = Click; 
     EventHandler<EventArgs> converted; 
     if (!TryConvertDelegate(onclick, out converted)) 
      throw new Exception("failed"); 
    } 

    //The conversion of one delegate type to another 
    static bool TryConvertDelegate<TOldType, TNewType>(TOldType oldDelegate, out TNewType newDelegate) 
     where TOldType : class, System.ICloneable, System.Runtime.Serialization.ISerializable 
     where TNewType : class, System.ICloneable, System.Runtime.Serialization.ISerializable 
    { 
     if (!typeof(Delegate).IsAssignableFrom(typeof(TOldType)) || !typeof(Delegate).IsAssignableFrom(typeof(TNewType))) 
      throw new ArgumentException(); //one of the types is not a delegate 

     newDelegate = default(TNewType); 
     Delegate handler = oldDelegate as System.Delegate; 
     if (handler == null) 
      return true; //null in, null out 

     Delegate result = null; 
     foreach (Delegate d in handler.GetInvocationList()) 
     { 
      object copy = System.Delegate.CreateDelegate(typeof(TNewType), d.Target, d.Method, false); 
      if (copy == null) 
       return false; // one or more can not be converted 
      result = System.Delegate.Combine(result, (System.Delegate)copy); 
     } 
     newDelegate = result as TNewType; 
     return (newDelegate != null); 
    } 
관련 문제