如何判断是否已设置枚举属性? C# [英] How to tell if an enum property has been set? C#

查看:248
本文介绍了如何判断是否已设置枚举属性? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类具有枚举属性的类:

I have a class with an enum property like so:

public class Foo
{
    public Color ColorType {get;set;}
}

public enum Color
{
    Red,
    Green,
}

现在可以像这样初始化该类:

Now this class can be initialized like so:

var foo = new Foo();

没有设置ColorType属性。
现在,我正在尝试创建一个方法并执行有关是否已设置该枚举的操作,例如,我有一个方法

without the ColorType property ever being set. Now, I'm trying to create a method and perform actions on whether that enum was ever set or not, for example I have a method

private void checkEnum(Foo foo)
{
    if(foo.ColorType !=null)
    {
        //perform these actions
    }else
    {
        //perform those actions
    }
}

,但是我收到警告说值永远不会为空,并且经过进一步的研究,如果枚举数从未设置过,如果默认为第一个值,在我的情况下
是红色,我在想关于向我的枚举中添加一个未设置的值并将该值设为第一个值,因此,如果尚未设置该值,则
枚举将具有未设置的值,是否有更好的方法这样做,我建议的方法似乎会变得混乱

however I get a warning saying that value will never be null and upon further research, if the enum is never set if will default to the first value which would be Red in my case, I was thinking about adding a value to my enum which would be 'not set' and make that value the first one, so if it hasnt been set then the enum will have the value 'not set', is there a better way of doing this, my proposed method seems like it could get messy

推荐答案

您可以使用以下两种方法之一:默认枚举值或a可空的枚举。

You can use one of two methods: default enum value or a nullable enum.

默认枚举va lue

由于枚举由整数支持,并且 int 默认为零,因此该枚举默认情况下将始终初始化为等于零的值。除非您明确分配枚举值,否则第一个值将始终为零,第二个值将始终为1,依此类推。

Since an enum is backed by an integer, and int defaults to zero, the enum will always initialize by default to the value equivalent to zero. Unless you explicitly assign enum values, the first value will always be zero, second will be one, and so on.

public enum Color
{
  Undefined,
  Red,
  Green
}

// ...

Assert.IsTrue(Color.Undefined == 0);  // success!

可为空的枚举

处理未分配枚举的另一种方法是使用可为空的字段。

The other way to handle unassigned enum is to use a nullable field.

public class Foo
{
   public Color? Color { get; set; }
}

// ...

var foo = new Foo();
Assert.IsNull(foo.Color);     // success!

这篇关于如何判断是否已设置枚举属性? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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