自IEnumerable<铸造;对象>到了IEnumerable<串GT; [英] Casting from IEnumerable<Object> to IEnumerable<string>
问题描述
最近我发现在C#中一个非常令人惊讶的行为。
我有这需要一种方法的IEnumerable<对象>
作为参数,我经过
的IEnumerable<串>
,但它是不可能的。
虽然在C#中一切都可以上溯造型比为什么这是不可能的对象吗?
这对我来说完全混乱。
请人清除我这个问题。
Recently I found a very surprising behavior in c#.
I had a method which takes IEnumerable<Object>
as a parameter and i was passing
IEnumerable<string>
but it's not possible.
While in c# everything can be upcast to Object than why this is not possible?
It's totally confusing for me.
Please someone clear me on this issue.
推荐答案
此的技术术语为泛型在C#3.0不变和更早版本。从C#4.0起,中投的作品。
The technical term for this is that generics are invariant in C# 3.0 and earlier. From C#4.0 onward, the cast works.
什么不变的手段是,有两个泛型类型之间没有任何关系,只是因为他们的泛型类型的参数相关(即是子或对方的超类型)
What invariant means is that there is no relationship between two generic types just because their generic type parameters are related (i.e. are sub- or supertypes of each other).
在你的榜样,有一个的IEnumerable℃之间没有打字关系;对象> ;
和的IEnumerable<串GT;
,只因为字符串是对象的子类型。他们只是考虑两个完全不相干的类型,如字符串和一个int(他们仍然都是对象的亚型,但一切)
In your example, there is no typing relationship between an IEnumerable<object>
and an IEnumerable<string>
, just because string is a subtype of object. They're just considered two completely unrelated types, like a string and an int (they still both are subtypes of object, but everything is)
有一些变通方法,并例外这个问题你已经碰上了。
There are a few workarounds and exceptions for this issue you've run into.
首先,你可以单独投每个字符串对象,如果你使用.NET 3.0,你可以做到这一点使用演员LT; T>()
扩展方法。否则,你可以使用foreach和结果放入你想要的静态类型的新变量。
First, you can cast each string individually to object, if you're using .NET 3.0 you can do that using the Cast<T>()
extension method. Otherwise, you can use a foreach and put the result into a new variable of the static type you want.
二,数组是引用类型的异常,即通过在字符串[]类型的方法acccepting对象[]类型应该工作。
Second, arrays are an exception for reference type, i.e. passing in a string[] type to a method acccepting object[] types should work.
这篇关于自IEnumerable<铸造;对象>到了IEnumerable<串GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!