似乎List对象不能存储在C#中的List变量中,甚至不能以这种方式显式转换.
List<string> sl = new List<string>();
List<object> ol;
ol = sl;
Run Code Online (Sandbox Code Playgroud)
结果无法隐式转换System.Collections.Generic.List<string>为System.Collections.Generic.List<object>
然后...
List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
Run Code Online (Sandbox Code Playgroud)
结果无法将类型转换System.Collections.Generic.List<string>为System.Collections.Generic.List<object>
当然,您可以通过从字符串列表中提取所有内容并将其一次放回一个来实现,但这是一个相当复杂的解决方案.
我的方案应该是简单的...我想要转换的类型FROM是ALWAYS "字符串".我想要转换为...可能是很多东西 - 整数,日期时间,...字符串等.
这很容易:
string valueToConvertFrom = "123";
int blah = Convert.ToInt32(valueToConvertFrom);
Run Code Online (Sandbox Code Playgroud)
但是......我不知道(直到运行时)我需要转换为的值是'Int'(或其他).我试过这个:
string valueToConvertFrom = "123";
Type convertToType = typeof(int);
object blah = Convert.ChangeType(valueToConvertFrom, convertToType);
Run Code Online (Sandbox Code Playgroud)
但这给了我以下错误:"对象必须实现IConvertible."
我不想做一个switch语句并根据类型名称调用"Convert.ToBlah"...任何建议?