.NET中的数组类型以及“是”和“==”之间的区别

时间:2017-01-10 12:49:39

标签: c#

阅读Jeffrey Richter的精彩文章Array Types in .NET 我意识到,C#数组(where()Int32[]等)的继承无法可视化。我的意思是,在VS中我看不到这些数组的基类。

还有一件有趣的事情:

String[]

bool b1 = Type.GetType("System.Int32[]").BaseType == typeof(System.Array); bool b2 = Type.GetType("System.Int32[]").BaseType is System.Array; b1不一样:b2b1trueb2

如何处理这种“神奇”以及其他与C#.NET相同的“魔法”?

1 个答案:

答案 0 :(得分:2)

运算符is比较一个对象是否兼容,或者可以转换为某种类型。 运算符==是相等运算符,它检查两个对象是否相等。

看一下这个例子

List<string> list = new List<string>() { "a", "b", "c" };
bool b = list is IList; //true
bool b2 = list.GetType() == typeof(IList<string>); //false

第一个bool变量为true,因为List<string>可以投放到IList<string>(事实上, IList<string>因为它实现了该接口)。第二个是false因为GetType()返回System.Collections.Generic.List 1 which is not equal to IList`