2013-09-03 2 views
0

제네릭을 사용하여 단일 확장 메서드 뒤에 전체 메서드 집합을 숨기려고합니다. 이러한 레거시 메서드는 모두 GetValidXXX라고하며 비슷한 서명이 있습니다 (그렇습니다. 실제로는 ,, 참조). 이전 버전과의 호환성을 위해 이전 GetValidXXX를 유지해야합니다.일반 확장 메서드로 형식 변환이 일치하지 않습니다.

public static T GetAttributeValue<T>(this DbElement element, DbAttribute attribute, T defaultValue) 
    { 
     T result = default(T); 
     if (typeof(T) == typeof(DbAttribute)) 
     { 
      if (element.GetValidAttribute(attribute, ref result)) return result; 
     } 
     else if (typeof(T) == typeof(bool)) 
     { 
      if (element.GetValidBool(attribute, ref result)) return result; 
     } 

     return defaultValue; 
    } 

결과는 특정 GetValidXXX 서명의 유형과 일치하지 않기 때문에이 컴파일되지 않습니다 (반환 값이 성공/실패).

bool GetValidAttribute(DbAttribute attribute, ref DbAttribute result) 
bool GetValidBool(DbAttribute attribute, ref bool result) 
etc 

어떻게 예는 다음과 같습니다 코드를 작성할 수 있도록하기위한 내가 목표로하고 무엇을 달성하기 위해이를 작성할 수 있습니다

string description = element.GetAttributeValue(DbAttributeInstance.DESC, "unset"); 
bool isWritable = !element.GetAttributeValue(DbAttributeInstance.READONLY, true); 

답변

3

당신은 당신의 심판 매개 변수에 대한 T를 사용할 수 없습니다 때문에 컴파일러는 항상 그 타입이 될 것이라고 보장 할 수 없다. 다음과 같이해야합니다.

public static T GetAttributeValue<T>(this DbElement element, DbAttribute attribute, T defaultValue) 
{ 
    if (typeof(T) == typeof(DbAttribute)) 
    { 
     var dbAttribute = default(DbAttribute); 
     if (element.GetValidAttribute(attribute, ref dbAttribute)) return (T)(object)dbAttribute; 
    } 
    else if (typeof(T) == typeof(bool)) 
    { 
     var boolResult = default(bool); 
     if (element.GetValidBool(attribute, ref boolResult)) return (T)(object)boolResult; 
    } 

    return defaultValue; 
} 
+0

이중 캐스트는 내가 여기 필요한 것입니다. –

1

Convert.ChangeType()이 유용 할 수 있습니다.

가능한 사용은 :

public static T ConvertTypeOrGetDefault<T>(this object value, T defaultValue) 
    { 
     try 
     { 
      return (T)Convert.ChangeType(value, typeof(T)); 
     } 
     catch (Exception ex) 
     { 
      return default(T); 
     } 
    } 

그것은 당신이 될 의사가있는 "해키"에 따라 달라집니다. 또한 기존 방법을 숨길 필요가 없도록 다시 고려할 수도 있습니다.

+0

감사합니다. 리팩토링은 저의 장기 목표입니다. 그러는 동안 필요가 깨지면 안됩니다. –

관련 문제