【发布时间】:2015-04-17 16:10:54
【问题描述】:
所以我的代码中有一个方法,其中一个参数是IEnumerable<object>。为清楚起见,这将是示例的唯一参数。我最初是用List<string> 的变量调用它,但后来意识到我只需要chars 并将变量的签名更改为List<char>。然后我在程序中收到一条错误消息:
Cannot convert source type 'System.Collections.Generic.List<char>'
to target type 'System.Collections.Generic.IEnumerable<object>'.
在代码中:
// This is the example of my method
private void ConversionExample(IEnumerable<object> objs)
{
...
}
// here is another method that will call this method.
private void OtherMethod()
{
var strings = new List<string>();
// This call works fine
ConversionExample(strings);
var chars = new List<char>();
// This will blow up
ConverstionExample(chars);
}
我可能想到的唯一原因是为什么第一个可以工作,但第二个不行是因为List<char>() 可以转换为string?我真的不认为会是这样,但这是我能做出的关于为什么这不起作用的唯一长期猜测。
【问题讨论】:
-
字符不是对象,字符串是
-
@pm100 在 c# 中基本上不是所有的对象吗?
-
@LuckyLikey
char继承自ValueType继承自object,所以实际上char是object。 Read this for more info -
是的 - char 是 Object,但不是 List 的情况。我学到了一些东西