📌  相关文章
📜  C# 程序检查指定类型是否为数组

📅  最后修改于: 2022-05-13 01:55:23.152000             🧑  作者: Mango

C# 程序检查指定类型是否为数组

在 C# 中,数组是一组由通用名称引用的同类元素。所以在本文中,我们将讨论如何检查变量是否为数组类型。为此,我们使用 Type 类的IsArray属性。该属性用于判断指定类型是否为数组。如果指定的类型是数组,IsArray 属性将返回 true。否则,它将返回 false。

句法:

public bool IsArray{get;}

返回:如果值为数组则返回true,否则返回false。

方法

示例 1:

C#
array.GetType().IsArray


C#
// C# program to determine whether the
// specified type is an array or not
using System;
using System.Reflection;
 
class GFG{
     
static void Main()
{
     
    // Declare an array with size 5
    // of integer type
    int[] array1 = new int[5];
 
    // Check whether the variable is array or not
    // Using IsArray property
    if (array1.GetType().IsArray == true)
    {
        Console.WriteLine("Type is array");
    }
    else
    {
        Console.WriteLine("Type is not array");
    }
}
}


输出:

// C# program to determine whether the
// specified type is an array or not
using System;
using System.Reflection;
 
class GFG{
     
static void Main()
{
 
    // Declare and initializing variables
    int array1 = 45;
    string array2 = "GeeksforGeeks";
    int[] array3 = new int[3];
    double[] array4 = { 2.3, 4.5, 0.33 };
 
    // Check whether the variable is of array type or not
    // Using IsArray property
    Console.WriteLine("Is the type of array1 variable is array?" +
                      array1.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array2.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array3.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array4.GetType().IsArray);
}
}

示例 2:

C#

Type is array
输出
// C# program to determine whether the
// specified type is an array or not
using System;
using System.Reflection;
 
class GFG{
     
static void Main()
{
 
    // Declare and initializing variables
    int array1 = 45;
    string array2 = "GeeksforGeeks";
    int[] array3 = new int[3];
    double[] array4 = { 2.3, 4.5, 0.33 };
 
    // Check whether the variable is of array type or not
    // Using IsArray property
    Console.WriteLine("Is the type of array1 variable is array?" +
                      array1.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array2.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array3.GetType().IsArray);
    Console.WriteLine("Is the type of array2 variable is array?" +
                      array4.GetType().IsArray);
}
}