使用枚举值 [英] Using Enum values
问题描述
我创建了一个.cs文件,添加了一个公开枚举:
命名空间对象
{
public enum EntityType
{
ThirdParty = 1,
BankAccount = 2
}
}
我的SQL表中有引用数据:
我希望能够引用我的枚举:
if(EntityTypeId == Objects.EntityType.BankAccount)...
然而,我不能比较一个Int,一个Object.EntityType。
这怎么可以实现和一个很好的干净的方式?
您可以在枚举和int值之间进行转换,例如:
EntityType yourEnumValue =(EntityType)yourIntegerValueFromDatabase;
if(yourEnumValue == EntityType.BankAccount)...
我应该指出,如果整数的值对您的枚举无效,您将收到一个异常抛出。你可以抓住它并处理它(不是首选),或者你可以使用IsDefined方法来测试该值是否有效。
if(Enum.IsDefined(typeof(EntityType),yourIntegerValueFromDatabase))
/ pre>
{
yourEnumValue =(EntityType)yourIntegerValueFromDatabase;
}
else
{
//以其他方式处理它,也许使用默认值
}
I would like to have some enums available in my web application. I have a sharedlib type class which has all my DTOs and is referenced by all layers, so I will put it in that project.
I created a .cs file, and added a public enum:
namespace Objects { public enum EntityType { Thirdparty = 1, BankAccount = 2 } }
I have reference data in my SQL table:
I'd like to be able to reference my enums like this:
if(EntityTypeId==Objects.EntityType.BankAccount) ...
However, I can't compare an Int, to an Object.EntityType.
How can this be achieved and a nice clean way? Constants instead?
解决方案You can cast between your enum and int values, for example:
EntityType yourEnumValue = (EntityType)yourIntegerValueFromDatabase; if (yourEnumValue == EntityType.BankAccount) ...
I should point out that if the value of the integer is not valid for your enum you will get an exception thrown. You can either catch this and deal with it (not preferred), or you can use the IsDefined method to test whether the value would work.
if (Enum.IsDefined(typeof(EntityType), yourIntegerValueFromDatabase)) { yourEnumValue = (EntityType)yourIntegerValueFromDatabase; } else { // deal with it some other way, perhaps use a default value }
这篇关于使用枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!