使用枚举值 [英] Using Enum values

查看:140
本文介绍了使用枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Web应用程序中提供一些枚举。我有一个sharedlib类,它具有所有的DTO,并被所有层引用,所以我将它放在该项目中。



我创建了一个.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))
{
yourEnumValue =(EntityType)yourIntegerValueFromDatabase;
}
else
{
//以其他方式处理它,也许使用默认值
}
/ pre>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆