This question already has answers here:
Why covariance and contravariance do not support value type
                                
                                    (4个答案)
                                
                        
                                4年前关闭。
            
                    
所以我的代码中有一个方法,其中参数之一是IEnumerable<object>。为了清楚起见,这将是该示例的唯一参数。我最初用一个List<string>变量来调用它,但是后来意识到我只需要那些是char并将变量的签名更改为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吗?我真的不这么认为,但这是我只能作长此猜测的唯一原因。

最佳答案

通用参数协方差不支持值类型。它仅在泛型参数为引用类型时才有效。

您可以使ConversionExample通用并接受IEnumerable<T>而不是IEnumerable<object>,或使用Cast<object>List<char>转换为IEnumerable<object>

关于c# - 无法将List <char>作为参数传递给List <object>? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29704342/

10-11 13:48
查看更多