通用投射CSV到列表

Meh*_*dad 0 c# csv casting

我已经编写了这个方法来将逗号分隔的字符串转换为其类型的List:

public List<T> GetListFromString<T>(string commaSplited)
{
  return commaSplited.Split(',').Cast<T>().ToList();
}
Run Code Online (Sandbox Code Playgroud)

但它引发了一个例外,说"指定的演员阵容无效".
我用长输入测试了它.

Eri*_* J. 7

如果T字符串(我测试过),你的代码肯定有用.

如果T其他东西,比如int,你会得到这个例外.

这个作品

List<string> result = GetListFromString<string>("abc, 123, hij");
Run Code Online (Sandbox Code Playgroud)

这很失败

List<int> resultInt = GetListFromString<int>("23, 123, 2");
Run Code Online (Sandbox Code Playgroud)

那是因为无法将字符串转换或转换为int,例如以下内容也会失败:

int three = (int)"3";
Run Code Online (Sandbox Code Playgroud)

修复

public List<T> GetListFromString<T>(string commaSplited)
    {
        return (from e in commaSplited.Split(',') 
                select (T)Convert.ChangeType(e, typeof(T))).ToList();
    }
Run Code Online (Sandbox Code Playgroud)

但是,所有给定的字符串必须可以转换为T,例如,以下内容仍然会失败:

List<int> resultIntFail = GetListFromString<int>("23, abc, 2");
Run Code Online (Sandbox Code Playgroud)

因为"abc"无法转换为int类型.

此外,T必须是System.Convert()知道如何从字符串转换为的某种类型.