【发布时间】:2011-11-15 23:10:07
【问题描述】:
[编辑:我的歉意...最初的问题措辞含糊不清,我没有得到我正在寻找的答复]
对于任何继承自类 Y 的类 X,new List<X>() is IEnumerable<Y> 为真。但是,这不适用于结构:new List<int>() is IEnumerable<ValueType> 是错误的。我的问题是:为什么?
这是一个示例程序:
class Program
{
class Y { }
class X : Y { }
struct Z { }
static void Main(string[] args)
{
Test(new List<X>());
Test(new List<string>());
Test(new List<Z>());
Test(new List<int>());
Test("blah");
Test(1);
Console.ReadLine();
}
static void Test(object o)
{
if (o is IEnumerable<Y>)
{
Console.WriteLine(o + " is a list of Ys");
}
else if (o is IEnumerable<ValueType>)
{
Console.WriteLine(o + " is a list of ValueTypes");
}
else if (o is IEnumerable<object>)
{
Console.WriteLine(o + " is a list of objects");
}
else if (o is System.Collections.IEnumerable)
{
Console.WriteLine(o + " is most likely a list of ValueTypes or a string");
}
else
{
Console.WriteLine(o + " is not a list");
}
}
}
输出:
System.Collections.Generic.List`1[ConsoleApplication1.Program+X] 是 Ys 的列表
System.Collections.Generic.List`1[System.String] 是一个对象列表
System.Collections.Generic.List`1[ConsoleApplication1.Program+Z] 很可能是 ValueType 列表或字符串
System.Collections.Generic.List`1[System.Int32] 很可能是 ValueType 列表或字符串
blah 很可能是 ValueType 列表或字符串
1 不是列表
那么为什么new List<int> 不是IEnumerable<ValueType>?
【问题讨论】:
-
它们会导致错误的测试,因为它们是错误的。
-
@BenRobinson:为什么它们是假的?字符串数组不为假。 String 是一个对象,Int32 是一个 ValueType,它也是一个对象。是的,Int32 是一个结构体,但基数仍然是一个 ValueType
-
是的,但是您没有检查 int 是否为
ValueType,您正在检查 lArr 是否为IEnumerable<ValueType>或List<ValueType>而不是List<int>。 -
@BenRobinson:我认为你没有理解我的意思。如果 x 继承自 y,
new List<x>() is y应该为真。对于字符串和任何其他对象都是如此。对于 int 和任何其他 struct/ValueType 为 false。 -
不,如果 x 继承自 y,我认为你错过了我的观点,那么
ListList<x> is List<y>()对于任何类型都是不正确的