2012-11-30 2 views
3

BinaryReader Read 메서드를 일반적인 방법으로 사용하려고합니다. 런타임에만 읽을 데이터 유형을 알고 있습니다.BinaryReader를 사용하는 방법 동적 데이터를 읽는 방법을 읽으시겠습니까?

public static T ReadData<T>(string fileName) 
     { 
      var value = default(T); 

      using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) 
      { 
       using (var reader = new BinaryReader(fs)) 
       { 
        if (typeof (T).GetGenericTypeDefinition() == typeof (Int32)) 
        { 
         value = (dynamic) reader.ReadInt32(); 
        } 
        if (typeof (T).GetGenericTypeDefinition() == typeof (string)) 
        { 
         value = (dynamic) reader.ReadString(); 
        } 
        // More if statements here for other type of data 
       } 
      } 
      return value ; 
     } 

어떻게 여러 if 문을 피할 수 있습니까?

+0

거기에'GetGenericTypeDefinition'에 대한 호출은 무엇입니까? 'T'가 제네릭 타입이라면, 제네릭 타입 정의가 아니기 때문에'System.Int32' 또는'System.String'에서 생성되지 않았을 것입니다. 반면,'T' *가 *'Int32' 또는'String' 인 경우,'GetGenericTypeDefinition'은 비 제네릭 타입에서 호출 할 때'InvalidOperationException'을 던집니다. –

+0

또한 제네릭을 사용하지 않는 방법의 좋은 예입니다. 지원할 모든 유형의 오버로드가 더 나은 해결책입니다. 체인 된'if'가 사용되지 않는 모든 수동 유형 확인이 필요합니다. –

답변

1
사전을 구축하는 것, (느린 것이다) 당신이 더 나은 것 같아서 내가 그 생각을 수있는 유일한 옵션을 반사를 사용하는 것보다 다른

:

static object s_lock = new object(); 
static IDictionary<Type, Func<BinaryReader, dynamic>> s_readers = null; 
static T ReadData<T>(string fileName) 
{ 
    lock (s_lock) 
    { 
     if (s_readers == null) 
     { 
      s_readers = new Dictionary<Type, Func<BinaryReader, dynamic>>(); 
      s_readers.Add(typeof(int), r => r.ReadInt32()); 
      s_readers.Add(typeof(string), r => r.ReadString()); 
      // Add more here 
     } 
    } 

    if (!s_readers.ContainsKey(typeof(T))) throw new ArgumentException("Invalid type"); 

    using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) 
    using (var reader = new BinaryReader(fs)) 
    { 
     return s_readers[typeof(T)](reader); 
    } 
} 

당신이 청소기 될 것입니다이 전화 코드 하지만 각 읽기 기능을 유형에 매핑해야하는 번거 로움이 있습니다.

+0

고맙습니다. 제 코드를 더 깨끗하게 만들 것입니다. – Monica