C# 在winforms中使用c访问枚举类型时出错
嗨,我对枚举类型有问题 我是这样做的C# 在winforms中使用c访问枚举类型时出错,c#,winforms,enums,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_SelectedIndexCha
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*type2=0-500,type3=500-1000*,type4=1000+say不能隐式地将类型字符串转换为int
如何将它们定义为enum
如何访问和比较listviewcategoriesitems
请任何人帮忙……您不能将枚举定义为字符串值-枚举实际上是命名的数字。如果需要字符串常量,只需使用:
public const string Type1 = "ALL";
public const string Type2 = "0-500";
。。。等等。如果您需要一个枚举用于其他地方,您可以创建一个字典,也可以创建一个反向映射,或者在属性中用字符串修饰每个枚举值,例如[DescriptionALL],您可以在执行时检索该属性。这有点尴尬,但不是太难
还要注意的是,C是区分大小写的-没有可派生的类形式,因此,遵循下面的操作非常值得,以使您的代码更易于其他开发人员阅读。试试这个
public enum categorytype
{
ALL=1,
From0TO500=2,
From500To1000=3 ,
From1000=4
}
因此,您应该将lstviewcategories项的值更改为1、2、3和4
或者将lstviewcategories的SelectedValue强制转换为enum,然后进行比较
categorytype mycategorytype = (categorytype)[Enum].Parse(Typeof(categorytype),lstviewcategories.SelectedValue);
if(mycategorytype == categorytype.All)
{
..................
}
您不能将字符串值分配给枚举,它们是仅接受的数字,如int、byte、long等 如上所述,枚举可以基于简单的数值类型
字节、sbyte、short、ushort、int、uint、long或ulong
因此,不要像您的定义中那样使用字符串。您可以使用struct:
categorytype mycategorytype = (categorytype)[Enum].Parse(Typeof(categorytype),lstviewcategories.SelectedValue);
if(mycategorytype == categorytype.All)
{
..................
}
struct CategoryType
{
public const string Type1 = "ALL";
public const string Type2 = "0-500";
public const string Type3 = "500-1000";
public const string Type4 = "1000+";
}