相关疑难解决方法(0)

在C#中,为什么List <string>对象不能存储在List <object>变量中

似乎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>

当然,您可以通过从字符串列表中提取所有内容并将其一次放回一个来实现,但这是一个相当复杂的解决方案.

.net c# generics covariance type-safety

83
推荐指数
6
解决办法
7万
查看次数

如何在运行时转换类型?

我的方案应该是简单的...我想要转换的类型FROMALWAYS "字符串".我想要转换为...可能是很多东西 - 整数,日期时间,...字符串等.

这很容易:

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"...任何建议?

.net reflection runtime type-conversion

21
推荐指数
3
解决办法
1万
查看次数