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 문을 피할 수 있습니까?
거기에'GetGenericTypeDefinition'에 대한 호출은 무엇입니까? 'T'가 제네릭 타입이라면, 제네릭 타입 정의가 아니기 때문에'System.Int32' 또는'System.String'에서 생성되지 않았을 것입니다. 반면,'T' *가 *'Int32' 또는'String' 인 경우,'GetGenericTypeDefinition'은 비 제네릭 타입에서 호출 할 때'InvalidOperationException'을 던집니다. –
또한 제네릭을 사용하지 않는 방법의 좋은 예입니다. 지원할 모든 유형의 오버로드가 더 나은 해결책입니다. 체인 된'if'가 사용되지 않는 모든 수동 유형 확인이 필요합니다. –