这是我写的一个片段,用于将逗号列表转换为T:
数组public static T[] ToArray<T>(this string s, params char[] seps)
{
if (typeof(T) == typeof(int))
{
return s.Split(seps.Length > 0 ? seps : new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(id => int.Parse(id))
.Cast<T>()
.ToArray();
}
else throw new Exception("cannot convert to " + typeof(T).Name);
}
我需要为每个我想支持的类型添加一个案例。
有没有更好的方法来编写这种东西?
答案 0 :(得分:4)
您可以随时执行以下操作:
public static T[] ToArray<T>(this string s, Func<string, T> converter, params char[] seps)
{
return s.Split(seps.Length > 0 ? seps : new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(converter)
.ToArray();
}
你可以这样称呼:
"1,2,3".ToArray(int.Parse, ',', ';');
我同意.Parse略显难看,但它为您提供了所需数据类型的灵活性......
答案 1 :(得分:2)
如果您将T
约束为IConvertible
,则可以使用ToType:
public static T[] ToArray<T>(this string s, params char[] seps)
where T : IConvertible
{
Type targetType = typeof(T);
return s.Split(seps.Length > 0 ? seps : new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Cast<IConvertible>()
.Select(ic => ic.ToType(targetType, CultureInfo.InvariantCulture))
.Cast<T>()
.ToArray();
}
答案 2 :(得分:0)
您可以尝试:
public static T[] ToArray<T>(this string s, Func<string, T> convert, char[] seps)
{
char[] separators = seps != null && seps.Length > 0 ? seps : new[] { ',' };
T[] values = s.Split(separators, StringSplitOptions.RemoveEmptyEntries)
.Select(x => convert(x))
.ToArray()
;
return values;
}
只需传递一名代表进行转换:
int[] Xs = "1,2,3".ToArray<int>(int.Parse , ',' , '-' , '/' , '|');