2013-12-20 4 views
3

는 다음 사항을 고려대해서 typeof와 기본 클래스

class Base 
    { 
     public int id { get; set; } 
    } 

    class Sub1 : Base 
    { 
     public int x { get; set; } 
     public int y { get; set; } 
    } 

    class Sub2 : Base 
    { 
     public string x { get; set; } 
     public string y { get; set; } 
    } 

    class Wrapper 
    { 
     public int x { get; set; } 
     public Sub1 sub1 { get; set; } 
     public Sub2 sub2 { get; set; } 
    } 

내가 뭘하려고 다음, 난이 기능에서 CLR 형식

private static Dictionary<Type, SqlDbType> types; 
    public static SqlDbType GetSqlDbType(Type type, string propertyName) 
    { 
     if (types == null) 
     { 
      types = new Dictionary<Type, SqlDbType>(); 
      types.Add(typeof(Int32), SqlDbType.Int); 
      types.Add(typeof(Int32?), SqlDbType.Int); 
      types.Add(typeof(decimal), SqlDbType.Decimal); 
      //etc 
      //the problem is here i want to return SqlDbType.VarBinary for every class that inherits Base 
      types.Add(typeof(Base), SqlDbType.VarBinary); 
     } 
     return types[type]; 
    } 

에서 SQL 유형을 얻기 위해이 유틸리티 기능이 있습니다 형식이 기본 클래스에서 상속 된 경우 SqlDbType.VarBinary를 반환하고 싶습니다. 이것이 가능합니까?

+4

해보십시오 일지 어떨지를 할 수있다() – Liath

답변

1

사전의 유형은 상속의 영향을받지 않는 모든 값 유형 인 것 같습니다. 이는 stringSqlDbType.NVarChar에 추가하더라도 그대로 유지됩니다. 그 때문에, 당신은 간단하게 수행 할 수 있습니다

private static Dictionary<Type, SqlDbType> types; 

public static SqlDbType GetSqlDbType(Type type, string propertyName) 
{ 
    if (types == null) 
    { 
     types = new Dictionary<Type, SqlDbType>(); 
     types.Add(typeof(Int32), SqlDbType.Int); 
     types.Add(typeof(Int32?), SqlDbType.Int); 
     types.Add(typeof(decimal), SqlDbType.Decimal); 
     // etc 
    } 

    SqlDbType result; 

    if (types.TryGetValue(type, out result)) 
    { 
     return result; 
    } 
    else 
    { 
     return SqlDbType.VarBinary; 
    } 
} 

다른 방법으로,

if (types.TryGetValue(type, out result)) 
    { 
     return result; 
    } 
    else if (typeof(Base).IsAssignableFrom(type)) 
    { 
     return SqlDbType.VarBinary; 
    } 
    else 
    { 
     // whatever, for example: 
     throw new ArgumentException(type); 
    } 
6

네, 그렇지만 실제 예보다 약간 복잡 할 것입니다. 빠른 예 :

typeof(int?).IsAssignableFrom(typeof(int)) 

일지 어떨지 방법은 두 가지 유형 사이의 암시 적 캐스팅이 있는지 확인할 수 있습니다 - 상속 된 클래스의 경우,이 주어진된다. 별도로 모든 단일 가능성을 확인해야하고, 적절한 순서로 - 당신이 볼 수 그래서 당신이 당신이 더 이상 유형에 대한 사전을 사용할 수 없음을 의미합니다, 그러나

typeof(Base).IsAssignableFrom(type) 

을 말할 수있다. 가장 쉬운 방법은 일부 유형을 단순 (사전 조회) 및 일부 지원 상속 (기본 유형 목록)으로 처리하는 것입니다.