Unable to pass List<char> to List<object> as a parameter?
本问题已经有最佳答案,请猛点这里访问。
所以我在代码中有一个方法,其中一个参数是
1 2 | Cannot convert source type 'System.Collections.Generic.List<char>' to target type 'System.Collections.Generic.IEnumerable<object>'. |
在代码中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 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); } |
我能想到的唯一原因是,为什么第一个会起作用,但第二个不会起作用,是因为
泛型参数协方差不支持值类型;它只在泛型参数是引用类型时工作。
您可以使
这是我的解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // 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); } |