모든 문자열을 강력한 형식의 목록으로 분할 할 수있는 분할 확장을 만들고 싶습니다. 나는 머리를 짚지 만, 많은 프로젝트에서 이것을 재사용 할 것이기 때문에 공동체로부터 의견을 얻고 싶습니다. (그래서 당신 자신의 도구 상자에 추가 할 수 있습니다.) 여기에서 아이디어가 있습니까?일반 유형의 스플릿 문자열 확장?
public static class Converters
{
public static IEnumerable<T> Split<T>(this string source, char delimiter)
{
var type = typeof(T);
//SPLIT TO INTEGER LIST
if (type == typeof(int))
{
return source.Split(delimiter).Select(n => int.Parse(n)) as IEnumerable<T>;
}
//SPLIT TO FLOAT LIST
if (type == typeof(float))
{
return source.Split(delimiter).Select(n => float.Parse(n)) as IEnumerable<T>;
}
//SPLIT TO DOUBLE LIST
if (type == typeof(double))
{
return source.Split(delimiter).Select(n => double.Parse(n)) as IEnumerable<T>;
}
//SPLIT TO DECIMAL LIST
if (type == typeof(decimal))
{
return source.Split(delimiter).Select(n => decimal.Parse(n)) as IEnumerable<T>;
}
//SPLIT TO DATE LIST
if (type == typeof(DateTime))
{
return source.Split(delimiter).Select(n => DateTime.Parse(n)) as IEnumerable<T>;
}
//USE DEFAULT SPLIT IF NO SPECIAL CASE DEFINED
return source.Split(delimiter) as IEnumerable<T>;
}
}
나는 변환 기능에 대한 매개 변수를 추가 할 것
여러 개의 단일 if 문 대신에 else를 사용해야합니다. 오직 하나만 일치 할 것입니다. – mfussenegger
@mfussenegger : 각'if' 블록에'return' 문이 있기 때문에'else'가 중복됩니다. – Douglas
일반 메서드가 제네릭 매개 변수의 형식을 테스트하는 데 의존하는 경우 IMO는 제네릭의 적절한 후보가 아닙니다. – spender