无法将List <char>作为参数传递给List <object>?

kri*_*gar 2 c# boxing object char

所以我的代码中有一个方法,其中一个参数是a IEnumerable<object>.为清楚起见,这将是该示例的唯一参数.我最初用一个变量来调用它List<string>,但后来意识到我只需要那些char变量,并将变量的签名更改为List<char>.然后我在程序中收到错误说:

Cannot convert source type 'System.Collections.Generic.List<char>'
to target type 'System.Collections.Generic.IEnumerable<object>'.
Run Code Online (Sandbox Code Playgroud)

在代码中:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

我可能想到为什么第一个会起作用的唯一原因,但第二个不会是因为a List<char>()可以转换为string?我真的不认为那会是它,但这是我唯一可以做出的关于为什么这不起作用的长期猜测.

Ser*_*rvy 6

通用参数协方差不支持值类型; 它仅在泛型参数是引用类型时有效.

你可以制作ConversionExample泛型并接受IEnumerable<T>而不是IEnumerable<object>,或者Cast<object>用来转换List<char>IEnumerable<object>.