[英]Generic Cast CSV to List
I've written this method to cast a comma separated string into a List of its type: 我已经编写了此方法,将逗号分隔的字符串转换为其类型的List:
public List<T> GetListFromString<T>(string commaSplited)
{
return commaSplited.Split(',').Cast<T>().ToList();
}
But it throws an exception saying 'The specified cast is not valid.' 但是它引发了一个异常,说“指定的转换无效。”
I've tested it with long input. 我已经用长输入测试了它。
Your code certainly works if T is string (I tested it). 如果T是字符串 (我已对其进行测试),则您的代码当然可以工作。
If T is something else , say int , you will get this Exception. 如果T是其他内容 ,请说int ,您将得到此异常。
This Works 这个作品
List<string> result = GetListFromString<string>("abc, 123, hij");
This Fails 失败了
List<int> resultInt = GetListFromString<int>("23, 123, 2");
That is because one cannot cast or convert string to int , eg the following would fail too: 那是因为不能将字符串 强制转换或转换为int ,例如,以下操作也会失败:
int three = (int)"3";
The Fix 修复
public List<T> GetListFromString<T>(string commaSplited)
{
return (from e in commaSplited.Split(',')
select (T)Convert.ChangeType(e, typeof(T))).ToList();
}
However all of the given strings must be convertable to T , eg the following would still fail: 但是,所有给定的字符串必须都可以转换为T ,例如,以下操作仍然会失败:
List<int> resultIntFail = GetListFromString<int>("23, abc, 2");
because "abc" cannot be converted to type int . 因为“ abc”无法转换为int类型。
Also, T must be some type that System.Convert() knows how to convert to from a string . 另外, T必须是System.Convert()知道如何从string转换为的某种类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.