如何将枚举设置为空 [英] How to set enum to null

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

问题描述

我有一个枚举

string name;

public enum Color
{
  Red,
  Green,
  Yellow
}

如何在加载时将其设置为 NULL.

How to set it to NULL on load.

name = "";
Color color = null; //error

我的错,我没有正确解释它.但是所有与 nullable 相关的答案都是完美的.我的情况是如果,我在一个类中使用其他元素(如名称等)获取/设置枚举.在页面加载时,我初始化类并尝试将值默认为空.这是场景(代码在 C# 中):

Edited: My bad, I didn't explain it properly. But all the answers related to nullable is perfect. My situation is What if, I have get/set for the enum in a class with other elements like name, etc. On page load I initiallize the class and try to default the values to null. Here is the scenario (Code is in C#):

namespace Testing
{
    public enum ValidColors
    {
        Red,
        Green,
        Yellow
    }

    public class EnumTest
    {
        private string name;
        private ValidColors myColor;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public ValidColors MyColor
        {
            get { return myColor; }
            set { myColor = value; }
        }

    }

    public partial class _Default : System.Web.UI.Page
    {       
        protected void Page_Load(object sender, EventArgs e)
        {
            EnumTest oEnumTest = new EnumTest();
            oEnumTest.Name = "";
            oEnumTest.MyColor = null; //???
        }
    }

}

然后使用下面的建议我更改了上面的代码以使其与 get 和 set 方法一起使用.我只需要添加?"在 EnumTest 类中声明私有枚举变量和 get/set 方法:

Then using the suggestions below I changed the above code to make it work with get and set methods. I just need to add "?" in EnumTest class during declaration of private enum variable and in get/set method:

public class EnumTest
{
    private string name;
    private ValidColors? myColor; //added "?" here in declaration and in get/set method

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public ValidColors? MyColor
    {
        get { return myColor; }
        set { myColor = value; }
    }

}

感谢大家的可爱建议.

推荐答案

您可以使用?"可空类型的运算符.

You can either use the "?" operator for a nullable type.

public Color? myColor = null;

或者通过将枚举中的第一个值(又名 0)作为默认值来使用不能为空的枚举的标准做法.例如在颜色为 None 的情况下.

Or use the standard practice for enums that cannot be null by having the FIRST value in the enum (aka 0) be the default value. For example in a case of color None.

public Color myColor = Color.None;

这篇关于如何将枚举设置为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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