【发布时间】:2015-03-29 18:21:34
【问题描述】:
我能够将逗号分隔的字符串转换为 IList<int>,但我如何修改它以获得 IList<T> 其中 T 将作为输入参数之一传递?
即如果我需要IList<int>,我将传递“int”作为参数,如果我需要IList<string>,我将传递“string”作为参数。
我的想法是通过输入参数获取类型是int还是string,并使用反射并将字符串转换为相应的列表
将逗号分隔的字符串转换为IList<int>
public static IList<int> SplitStringUsing(this string source, string seperator =",")
{
return source.Split(Convert.ToChar(seperator))
.Select(x => x.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(int.Parse).ToList();
}
注意:以上代码尚未测试
我正在寻找类似的东西
public static IList<T> SplitStringUsing(this string source, string seperator =",", T t)
{
find the type of t and convert it to respective List
}
【问题讨论】:
-
如果使用 IsNullOrWhitespace,则无需修剪。
-
不提供参数
T t,而是提供一个“选择器”函数Func<string, T>,然后用它代替int.Parse,怎么样?所以你可以像IList<int> list = "1, 2, 3, 4".SplitStringUsing(",", int.Parse);一样使用它。如果您需要例如双打,您可以将其更改为IList<double> list = "1, 2, 3, 4".SplitStringUsing(",", double.Parse);。
标签: c# string reflection collections