C# 枚举和常量应用区别是什么呢?
当我们需要定义的时候呢,优先考虑枚举。
在C#中,枚举的真正强大之处是它们在后台会实例化为派生于基类System.Enum的结构。这表示可以对它们调用方法,执行有用的任务。注意因为.NET Framework的执行方式,在语法上把枚举当做结构是不会有性能损失的。实际上,一旦代码编译好,枚举就成为基本类型,与int和float类似。
但是在实际应用中,你也许会发现,我们经常用英语定义枚举类型,因为开发工具本来就是英文开发的,美国人用起来,就直接能够明白枚举类型的含义。其实,我们在开发的时候就多了一步操作,需要对枚举类型进行翻译。没办法,谁让编程语言是英语写的,如果是汉语写的,那我们也就不用翻译了,用起枚举变得很方便了。举个简单的例子,TimeOfDay.Morning一看到Morning,美国人就知道是上午,但是对于中国的使用者来说,可能有很多人就看不懂,这就需要我们进行翻译、解释,就向上面的getTimeOfDay()的方法,其实就是做了翻译工作。所以,在使用枚举的时候,感觉到并不是很方便,有的时候我们还是比较乐意创建常量,然后在类中,声明一个集合来容纳常量和其意义。
C# 枚举和常量之使用常量定义:这种方法固然可行,但是不能保证传入的参数day就是实际限定的。
using System;
using System.Collections.Generic;
//C# 枚举和常量应用区别
public class TimesOfDay
{
public const int Morning = 0;
public const int Afternoon = 1;
public const int Evening = 2;
public static Dictionary﹤int, string﹥ list;
/// ﹤summary﹥
/// 获得星期几
/// ﹤/summary﹥
/// ﹤param name="day"﹥﹤/param﹥
/// ﹤returns﹥﹤/returns﹥
public static string getTimeNameOfDay(int time)
{
if (list == null || list.Count ﹤= 0)
{
list = new Dictionary﹤int, string﹥();
list.Add(Morning, "上午");
list.Add(Afternoon, "下午");
list.Add(Evening, "晚上");
}
return list[time];
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
希望能够找到一种比较好的方法,将枚举转为我们想要的集合。搜寻了半天终于找到了一些线索。通过反射,得到针对某一枚举类型的描述。
C# 枚举和常量应用区别之枚举的定义中加入描述
using System;
using System.ComponentModel;
//C# 枚举和常量应用区别
public enum TimeOfDay
{
[Description("上午")]
Moning,
[Description("下午")]
Afternoon,
[Description("晚上")]
Evening,
};
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
C# 枚举和常量应用区别之获得值和表述的键值对
/// ﹤summary﹥
/// 从枚举类型和它的特性读出并返回一个键值对
/// ﹤/summary﹥
/// ﹤param name="enumType"﹥
Type,该参数的格式为typeof(需要读的枚举类型)
﹤/param﹥
/// ﹤returns﹥键值对﹤/returns﹥
public static NameValueCollection
GetNVCFromEnumValue(Type enumType)
{
NameValueCollection nvc = new NameValueCollection();
Type typeDescription = typeof(DescriptionAttribute);
System.Reflection.FieldInfo[]
fields = enumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
strValue = ((int)enumType.InvokeMember(
field.Name, BindingFlags.GetField, null,
null, null)).ToString();
object[] arr = field.GetCustomAttributes(
typeDescription, true);
if (arr.Length ﹥ 0)
{
DescriptionAttribute aa =
(DescriptionAttribute)arr[0];
strText = aa.Description;
}
else
{
strText = field.Name;
}
nvc.Add(strText, strValue);
}
} //C# 枚举和常量应用区别
return nvc;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
当然,枚举定义的也可以是中文,很简单的解决的上面的问题,但是,我们的代码看起来就不是统一的语言了。
ChineseEnum
public enum TimeOfDay
{
上午,
下午,
晚上,
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
C# 枚举和常量应用区别的基本情况就向你介绍到这里,希望对你了解和学习C# 枚举有所帮助。
【编辑推荐】