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

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

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

类是方法、变量和对象的集合。或者我们可以说类是创建对象的蓝图。因此,要检查指定的类型是否是类以及委托,我们使用 Type 类的 IsClass 属性。如果类型是类,它将返回 true。否则,它将返回 false(对于结构或枚举数)。它是一个只读属性。

语法

public bool IsClass { get; }

示例 1:

C#
// C# program to check the given
// type is a class or not
using System;
using System.Reflection;
 
// Declare a class
public class Student1
{
    public void myfun()
    {
        Console.WriteLine("I like DSA");
    }
}
 
// Declare delegates
public delegate void divnum(int x, int y);
 
// Declare structure
public struct Student2
{
    public int Id;
    public string Name;
}
 
public class GFG{
     
// Driver code
public static void Main(string[] args)
{
     
    // Check the given type is a class or not
    // Using IsClass property
    Console.WriteLine(typeof(Student1).IsClass);
    Console.WriteLine(typeof(divnum).IsClass);
    Console.WriteLine(typeof(Student2).IsClass);
}
}


C#
// C# program to check the given
// type is a class or not
using System;
using System.Reflection;
 
// Declare a class
public class Pet
{
    public void myfun()
    {
        Console.WriteLine("I like Dogs");
    }
}
 
public class GFG{
     
// Driver code
public static void Main(string[] args)
{
     
    // Check the given type is a class or not
    // Using IsClass property
    if (typeof(Pet).IsClass == true)
    {
        Console.WriteLine("The given type is a class");
    }
    else
    {
        Console.WriteLine("The given type is not a class");
    }
}
}


输出:

True
True
False

示例 2:

C#

// C# program to check the given
// type is a class or not
using System;
using System.Reflection;
 
// Declare a class
public class Pet
{
    public void myfun()
    {
        Console.WriteLine("I like Dogs");
    }
}
 
public class GFG{
     
// Driver code
public static void Main(string[] args)
{
     
    // Check the given type is a class or not
    // Using IsClass property
    if (typeof(Pet).IsClass == true)
    {
        Console.WriteLine("The given type is a class");
    }
    else
    {
        Console.WriteLine("The given type is not a class");
    }
}
}

输出:

The given type is a class