如何將枚舉設置爲空 - How to set enum to null

問題:

I have an enum我有一個枚舉

string name;

public enum Color
{
  Red,
  Green,
  Yellow
}

How to set it to NULL on load.如何在加載時將其設置爲 NULL。

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

Edited: My bad, I didn't explain it properly.編輯:我的錯,我沒有正確解釋。 But all the answers related to nullable is perfect.但是所有與 nullable 相關的答案都是完美的。 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#):這是場景(代碼在 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; //???
        }
    }

}

Then using the suggestions below I changed the above code to make it work with get and set methods.然後使用下面的建議我更改了上面的代碼以使其與 get 和 set 方法一起使用。 I just need to add "?"我只需要添加“?” in EnumTest class during declaration of private enum variable and in get/set method:在 EnumTest 類中,在私有枚舉變量的聲明和 get/set 方法中:

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; }
    }

}

Thanks all for the lovely suggestions.謝謝大家的可愛建議。


解決方案:

參考一: https://en.stackoom.com/question/ICIj
參考二: https://stackoom.com/question/ICIj
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章