访问枚举类型在winforms中使用c#时出错

时间:2011-08-25 09:04:09

标签: c# winforms enums

嗨我有枚举类型的问题

我这样做....

namspace XXXXXXxx
{
 public partial class form1:form
  {

          ////////
       and i am checking the listview selected item with enum type by the             following code
      private void lstviewcategories_SelectedIndexChanged(object sender, EventArgs e)
      {

          if (lstviewcategories.SelectedItems[0].ToString() == categorytype.type1.ToString())
            { 

                    /////
                       blah blah...
            }
       }
           and  at here i am defining enum like this...
    public enum categorytype
    {
       type1 = "ALL",
         type2 ="0-500",
       type3 ="500-1000" ,
        type4 ="1000+ "                    
    }
  }

}

我在这些行收到错误 type1 =“ALL”, t * ype2 =“0-500”,type3 =“500-1000” * ,type4 =“1000 +”表示无法将类型字符串隐式转换为int

我如何将它们定义为枚举

我如何访问并与listviewcategoriesitems进行比较.....

任何人都可以帮忙......

5 个答案:

答案 0 :(得分:2)

您无法将枚举定义为字符串值 - 枚举实际上是命名数字。如果你想要字符串常量,你只需要使用:

public const string Type1 = "ALL";
public const string Type2 = "0-500";

...等。如果你需要枚举用于其他地方,你可以创建一个Dictionary<CategoryType, string>,也可以创建一个反向映射,或用属性中的字符串装饰每个枚举值(例如{{ 1}})您可以在执行时检索它。这有点尴尬,但不是太难。

(另请注意,C#区分大小写 - 没有类[Description("ALL")]可以派生,并且值得关注.NET naming conventions以使其代码更容易为其他开发人员阅读。)

答案 1 :(得分:1)

您可以改为使用struct

struct CategoryType
{
    public const string Type1 = "ALL";
    public const string Type2 = "0-500";
    public const string Type3 = "500-1000";
    public const string Type4 = "1000+";
}

答案 2 :(得分:0)

试试这个

public enum categorytype
{
   ALL=1,
   From0TO500=2,
   From500To1000=3 ,
   From1000=4                    
}

因此您应该使用lstviewcategories

更改1,2,3, and 4项的值
if(lstviewcategories.SelectedValue == categorytype.All.ToString())
{
   .................. 
}

或将SelectedValue的{​​{1}}转换为枚举,然后比较

lstviewcategories

答案 3 :(得分:0)

您不能将String值分配给Enums,它们只接受诸如int,byte,long等的数字......。

答案 4 :(得分:0)

如上所述here on MSDNEnum可以基于简单的数值类型,

bytesbyteshortushortintuintlong或{{1} }

所以,不是ulong,就像你的定义一样。