제네릭을 사용하여 단일 확장 메서드 뒤에 전체 메서드 집합을 숨기려고합니다. 이러한 레거시 메서드는 모두 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);
이중 캐스트는 내가 여기 필요한 것입니다. –