【问题标题】:Unable to pass List<char> to List<object> as a parameter? [duplicate]无法将 List<char> 作为参数传递给 List<object>? [复制]
【发布时间】:2015-04-17 16:10:54
【问题描述】:

所以我的代码中有一个方法,其中一个参数是IEnumerable&lt;object&gt;。为清楚起见,这将是示例的唯一参数。我最初是用List&lt;string&gt; 的变量调用它,但后来意识到我只需要chars 并将变量的签名更改为List&lt;char&gt;。然后我在程序中收到一条错误消息:

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&lt;char&gt;() 可以转换为string?我真的不认为会是这样,但这是我能做出的关于为什么这不起作用的唯一长期猜测。

【问题讨论】:

标签: c# object char boxing


【解决方案1】:

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

您可以将ConversionExample 设为通用并接受IEnumerable&lt;T&gt; 而不是IEnumerable&lt;object&gt;,或者使用Cast&lt;object&gt;List&lt;char&gt; 转换为IEnumerable&lt;object&gt;

【讨论】:

    【解决方案2】:

    这将是我的解决方案:

    // This is the example of my method
    private void ConversionExample<T>(IEnumerable<T> objs)
    {
        ...
    }
    
    // here is another method that will call this method.
    private void OtherMethod()
    {
        var strings = new List<string>();
        // This call works fine
        ConversionExample<string>(strings);
    
        var chars = new List<char>();
        // This should work now
        ConversionExample<char>(chars);
    }
    

    【讨论】:

    • 这很酷,但它并不能真正回答为什么List&lt;string&gt; 有效而List&lt;char&gt; 无效,如果我理解正确的话,这就是问题
    • @LuckyLikey,另一个答案总结得很好。原始类型不是对象(它们可以装箱为 INTO 对象,但它们不是从对象派生的),因此如果不显式装箱,编译器无法推断您想要将原始类型隐式地装箱到对象类型中。
    • 是的,你是对的,我的评论应该被删除:)
    • @RonBeyer 这是错误的。首先,C# 没有术语“原始类型”的概念。其次,值类型(我假设您的意思是什么?)对象,它们确实派生自对象。 C# 中唯一不从 object 派生的类型是指针,在这种情况下不涉及。
    • @servy msdn.microsoft.com/en-us/library/aa711900%28v=vs.71%29.aspx 非常明确地定义了原始类型。我确实误解了一些东西,是的,这些类型是从对象派生的,但在它们被明确地装箱到对象中之前不会被视为对象。除非先装箱,否则无法将它们分配给 null,这一点非常明显。
    猜你喜欢
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2014-04-06
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多