C# 如何判断一个引用是数组类型?

string[] a;
int[] b;

// 这样可以判断,但是不是我想要的写法,因为is判断不仅限于类型相等,前者是后者的子类也返回true
// 虽然Array不会有子类,但是我希望写法和其他代码统一风格
if (a is Array){ .... // true
if (b is Array){ .... // true

// 我想要类似这样的写法
if (a.GetType() == typeof(Array)){ .... // false
// 但==左边是String[],右边是System.Array,等式不成立

// 我又不能写成
if (a.GetType() == typeof(string[])){ ... // true
// 因为不仅仅是string数组,int数组,其他数组都希望被检查出来
// 用object[]也不行
if (a.GetType() == typeof(object[])){ ... // false

要用GetType的方式来做其实不难,因为所有数组都是直接继承System.Array的。

[code="c#"]using System;

static class Demo {
static bool IsArray(this object o) {
return o is Array;
}

static bool IsArray2(this object o) {
    if (null == o) return false;
    return o.GetType().BaseType == typeof(Array);
}

static void Main(string[] args) {
    Console.WriteLine("args is array: {0}", args.IsArray());
    Console.WriteLine("args is array: {0}", args.IsArray2());
}

}[/code]
但这种情况下用is会比用GetType()快一些,所以我觉得没必要麻烦自己去把一个有内建运算符的东西写得那么长。

P.S. 如果是GetType()之后直接与一个typeof字面量比较的话,有机会比is快,像是:
[code="c#"]o.GetType() == typeof(string)[/code]
有机会比
[code="c#"]o is string[/code]
要快一些。

但如果GetType()之后还有附加的操作,或者比较的另一边不是typeof字面量的话,则总是比is慢。能用is的话还是推荐使用is运算符的。