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

xiaoxiao2026-09-12  11

问答原文: [i]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 [/i] 我的解答: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Reflection;namespace TypeCheck{ class Program { static void Main(string[] args) { string[] b = new string[] {"1", "2", "3"}; Console.WriteLine(typeof(string[])); Console.WriteLine("The type is {0}", b.GetType()); if (b.GetType().IsArray) Console.WriteLine("Its true"); else Console.WriteLine("ITs false"); if (b.GetType() == typeof(string[])) { Console.WriteLine("true"); } else { Console.WriteLine("false"); } Console.Read(); } }} RednaxelaFX的答案: 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()); }} 相关资源:敏捷开发V1.0.pptx
转载请注明原文地址: https://www.6miu.com/read-5052595.html

最新回复(0)