检查指定类型的 C# 程序是否为枚举
枚举或也称为枚举用于存储用户定义的数据。它用于将字符串值分配给一个整数常量,使程序易于阅读和管理。我们可以使用 enum 关键字后跟枚举名称来创建枚举数据。在 C# 中,我们可以通过使用 Type 类的 IsEnum 属性来检查特定类型是否为枚举。如果类型是枚举,它将返回 true。否则,此属性将返回 false。它是一个只读属性。
句法:
public bool IsEnum { get; }
返回类型:此属性的返回类型是布尔值。它将返回真或假。
示例 1:
C#
// C# program to check whether the
// given type is enum or not
using System;
using System.Reflection;
// Declare a enum type with subjects
enum Subject
{
Java, Python, Php, Html
}
class GFG{
// Driver code
public static void Main(string[] args)
{
// Check the given type is a enum or not
// Using IsEnum property
Console.WriteLine(typeof(Subject).IsEnum);
}
}
C#
// C# program to check whether the
// given type is enum or not
using System;
using System.Reflection;
enum courses
{
DSA, ReactJS, OperatingSystem, DBMS
}
class Branch
{
void display()
{
Console.WriteLine("Name of the branch");
}
}
struct subject
{
string name;
int marks;
}
class GFG{
// Driver code
public static void Main(string[] args)
{
// Check the given type is a enum or not
// Using IsEnum property
bool res1 = typeof(courses).IsEnum;
bool res2 = typeof(Branch).IsEnum;
bool res3 = typeof(subject).IsEnum;
Console.WriteLine("Is courses is enum?: " + res1);
Console.WriteLine("Is Branch is enum?: " + res2);
Console.WriteLine("Is subject is enum?: " + res3);
}
}
输出:
True
示例 2:
C#
// C# program to check whether the
// given type is enum or not
using System;
using System.Reflection;
enum courses
{
DSA, ReactJS, OperatingSystem, DBMS
}
class Branch
{
void display()
{
Console.WriteLine("Name of the branch");
}
}
struct subject
{
string name;
int marks;
}
class GFG{
// Driver code
public static void Main(string[] args)
{
// Check the given type is a enum or not
// Using IsEnum property
bool res1 = typeof(courses).IsEnum;
bool res2 = typeof(Branch).IsEnum;
bool res3 = typeof(subject).IsEnum;
Console.WriteLine("Is courses is enum?: " + res1);
Console.WriteLine("Is Branch is enum?: " + res2);
Console.WriteLine("Is subject is enum?: " + res3);
}
}
输出:
Is courses is enum?: True
Is Branch is enum?: False
Is subject is enum?: False