本文详细讲解了C#与C++枚举的区别对比和使用案例,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
C++与C#中枚举的区别
一、C++
- 枚举类型中的每个元素,可以直接使用,不必通过类型.元素的方式调用
- 没有++操作
#include <iostream>
using namespace std;
enum week{Monday,Thuesday};
int main()
{
week day;
day = Monday;
day = Thuesday;
//day = 4; 报错 类型转化出错
//day++; 出错,没有++ 操作
cout << day << endl;//输出结果为1
return 0;
}
二、C#
- 枚举类型中的每个元素必须通过类型.元素的形式调用
- 可以++操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myEnum_Structure
{
enum Week
{
Monday,
Thuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
class Program
{
static void Main(string[] args)
{
Week day;
day = Week.Sunday;
Console.WriteLine(day);//输出Sunday
day++;
Console.WriteLine(day);//输出7
}
}
}
C#枚举案例
一、普通调用
public enum NoticeType
{
Notice = 'A',
LabRule = 'H',
HotInformation = 'N',
Column = 'C',
All = '1',
Null = '0'
}
private void button1_Click(object sender, EventArgs e)
{
//新建枚举类型
NoticeType noticeType1 = NoticeType.Column;
//把枚举类型转换为string d="Column"
string d = noticeType1.ToString();
//取得枚举类型的基数 'C'
char dd = (char)noticeType1;
//通过基数取得对应的枚举类型
NoticeType noticeType2 = (NoticeType)Char.Parse("A");//Notice
//通过名称取得枚举类型
NoticeType noticeType3 = (NoticeType)Enum.Parse(typeof(NoticeType), "Notice");
}
二、获取描述信息
[Description("会员等级")]
enum MemberLevel
{
[Description("金牌会员")]
gold = 1,
[Description("银牌会员")]
silver = 2,
[Description("铜牌会员")]
copper = 3
}
/// <summary>
///
/// </summary>
/// <param name="value">枚举值</param>
/// <param name="isTop">是否是顶级标题的描述信息</param>
/// <returns></returns>
public static string GetDescription(this Enum value, bool isTop = false)
{
Type enumType = value.GetType();
DescriptionAttribute attr = null;
if (isTop)
{
attr = (DescriptionAttribute)Attribute.GetCustomAttribute(enumType, typeof(DescriptionAttribute));
}
else
{
// 获取枚举常数名称。
string name = Enum.GetName(enumType, value);
if (name != null)
{
// 获取枚举字段。
FieldInfo fieldInfo = enumType.GetField(name);
if (fieldInfo != null)
{
// 获取描述的属性。
attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute;
}
}
}
if (attr != null && !string.IsNullOrEmpty(attr.Description))
return attr.Description;
else
return string.Empty;
}
调用
MemberLevel gold = MemberLevel.gold;
Console.WriteLine(gold.GetDescription());
System.Console.Read();
到此这篇关于C#与C++枚举的区别对比和使用案例的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:C#与C++枚举的区别对比和使用案例


基础教程推荐
猜你喜欢
- Unity shader实现高斯模糊效果 2023-01-16
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C# 解析XML和反序列化的示例 2023-04-14
- C#中 Json 序列化去掉null值的方法 2022-11-18
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中的Linq to JSON操作详解 2023-06-08