现在的位置: 首页 > 综合 > 正文

.net下枚举的用法

2012年08月14日 ⁄ 综合 ⁄ 共 998字 ⁄ 字号 评论关闭
     在一次项目中需要把枚举的值添加到Combox中去,需要对枚举进行操作。经过学习总结如下,也便于以后查询:
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
1.根据name获得Enum的类型:
Colors mycolor = (Colors)Enum.Parse(typeof(Colors),"red",true);
(int)mycolor1=1
2.根据value获得Enum的类型:
Colors mycolor = (Colors)Enum.Parse(typeof(Colors),"1",true);
mycolor2.ToString()=Red
3.遍历枚举内容
foreach(string s in Enum.GetNames(typeof(Colors)))
{
    //to do
}
4.怎样确定一个名称或值是枚举中的一个
Enum.IsDefined(typeof(myenum),object(name or value))
5.怎样确定一个类型:  Type t = mycolor.GetType();
                   Type t1 =typeof(Colors);
                   Type t2 = Type.GetType("namespace.Colors");
补充:
Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Blue,Yellow");
The myOrange value has the combined entries of [myOrange.ToString()]=13

Colors myOrange2 = (Colors)Enum.Parse(typeof(Colors), "Red, Blue");
The myOrange2 value has the combined entries of [myOrange2.ToString()]=5

另:
x.gettype和typeof的用法
1.判断某个实例是否某个类型
  c#  o is classname
  vb   typeof o is classname//必须是引用类型。typeof且必须和is联用
2.c# typeof(int)
   bv gettype(integer)
3.object类的方法
   c# o.GetType
   vb  o.GetType

抱歉!评论已关闭.