C# C中select语句中具有相同整数值的枚举?
如何对下面的代码进行编码,以便用C进行编译?编译器错误是:此开关语句中已出现标签“case 3:” 这就足够了C# C中select语句中具有相同整数值的枚举?,c#,enums,switch-statement,C#,Enums,Switch Statement,如何对下面的代码进行编码,以便用C进行编译?编译器错误是:此开关语句中已出现标签“case 3:” 这就足够了 switch (customerType) { case CustomerType.Private: return externCustomerType.P; case CustomerType.Business: return externCustomerType.B; case CustomerType.Interstate:
switch (customerType)
{
case CustomerType.Private:
return externCustomerType.P;
case CustomerType.Business:
return externCustomerType.B;
case CustomerType.Interstate:
return externCustomerType.I;
default:
return externCustomerType.N;
}
由于海外和州际的值均为3,因此如果customerType具有其中一个值(实际上它只有3个值),则可以使用不同的枚举值分配相同的整数值
如果要独立于枚举的值,请将开关重写为ifs:
删除Overseas=3后面的逗号?并将枚举强制转换为int?case int CustomerType.Private:…添加整数是否有特定原因?如果不是,就把它们去掉!哦最后一个逗号是@failedprogramming!请参阅我的编辑。我已经纠正了那个错误。该错误实际上是因为最后两个枚举值具有相同的整数值。@hvd:我不满意,因为如果有人更改枚举类型的整数值,则我的代码将中断。@CJ7确实如此,但更改枚举应已被视为中断更改,对于其他代码,您确实是这样对待它的。有多种方法可以确保您的代码在枚举定义更改时出现编译时错误,这将很早发现任何中断,从而避免任何不正确的运行时行为。我对此不满意,因为如果有人更改枚举类型的整数值,则我的代码将中断。@CJ7 OK,您的另一个解决方案,请参阅我的更新。
switch (customerType)
{
case CustomerType.Private:
return externCustomerType.P;
case CustomerType.Business:
return externCustomerType.B;
case CustomerType.Interstate:
return externCustomerType.I;
default:
return externCustomerType.N;
}
if (customerType == CustomerType.Private)
return externCustomerType.P;
else if (customerType == CustomerType.Business)
return externCustomerType.B;
else if (customerType == CustomerType.Overseas || customerType == CustomerType.Interstate)
return externCustomerType.I;
else
return externCustomerType.N;