📜  C# 程序检查指定类型是否为值类型

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

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

在 C# 中,值类型表示位序列。它不是类或接口,它被称为结构或枚举(值类型的特殊情况)。因此,要检查指定的类型是否为值类型,我们使用 Type 类的 IsValueType 属性。它是一个只读属性。如果类型是值类型,它将返回 true。否则,它将返回 false。对于枚举,它将返回 true,但对于 Enum 类型不会返回 true。

语法

public bool IsValueType { get; }

示例 1:

C#
// C# program to check whether the specified
// type is a value type or not
using System;
using System.Reflection;
  
// Declare a structure
struct myStructure
{
      
    // Declaring a method 
    public static void display()
    {
        Console.WriteLine("Hello! GeeksforGeeks");
    }
}
  
// Declare a class
public class Geeks
{
      
    // Declaring a method 
    public static void show()
    {
        Console.WriteLine("Hey! GeeksforGeeks");
    }
      
}
  
public class GFG{
      
// Driver class
public static void Main(string[] args)
{
      
    // Checking the given type is a value type or not
    // Using IsValueType Property
    Console.WriteLine(typeof(myStructure).IsValueType);
    Console.WriteLine(typeof(Geeks).IsValueType);
}
}


C#
// C# program to check whether the specified
// type is a value type or not
using System;
using System.Reflection;
  
// Declare a structure
struct myGFG
{
      
    // Declaring a method 
    public static void display()
    {
        Console.WriteLine("Welcome to GeeksforGeeks");
    }
}
  
public class GFG{
      
// Driver class
public static void Main(string[] args)
{
      
    // Checking the given type is a value type or not
    // Using IsValueType Property
    if (typeof(myGFG).IsValueType == true)
    {
        Console.WriteLine("The given type is value type");
    }
    else
    {
        Console.WriteLine("The given type is not a value type");
    }
}
}


输出:

True
False

示例 2:

C#

// C# program to check whether the specified
// type is a value type or not
using System;
using System.Reflection;
  
// Declare a structure
struct myGFG
{
      
    // Declaring a method 
    public static void display()
    {
        Console.WriteLine("Welcome to GeeksforGeeks");
    }
}
  
public class GFG{
      
// Driver class
public static void Main(string[] args)
{
      
    // Checking the given type is a value type or not
    // Using IsValueType Property
    if (typeof(myGFG).IsValueType == true)
    {
        Console.WriteLine("The given type is value type");
    }
    else
    {
        Console.WriteLine("The given type is not a value type");
    }
}
}

输出:

The given type is value type