Programming

열거 형을 null로 설정하는 방법

procodes 2020. 5. 25. 22:37
반응형

열거 형을 null로 설정하는 방법


나는 열거 형이있다

string name;

public enum Color
{
  Red,
  Green,
  Yellow
}

로드시 NULL로 설정하는 방법

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

편집 : 내 나쁜, 나는 제대로 설명하지 않았다. 그러나 nullable과 관련된 모든 대답은 완벽합니다. 내 상황은 이름과 같은 다른 요소가있는 클래스에서 열거 형에 대해 가져 오거나 설정 한 경우입니다. 페이지로드에서 클래스를 초기화하고 기본값을 null로 설정하려고합니다. 시나리오는 다음과 같습니다 (코드는 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 메소드에서 :

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

}

멋진 제안에 감사드립니다.


"?"를 사용할 수 있습니다 널 입력 가능 유형의 연산자.

public Color? myColor = null;

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;

If this is C#, it won't work: enums are value types, and can't be null.

The normal options are to add a None member:

public enum Color
{
  None,
  Red,
  Green,
  Yellow
}

Color color = Color.None;

...or to use Nullable:

Color? color = null;

Make your variable nullable. Like:

Color? color = null;

or

Nullable<Color> color = null;

An enum is a "value" type in C# (means the the enum is stored as whatever value it is, not as a reference to a place in memory where the value itself is stored). You can't set value types to null (since null is used for reference types only).

That being said you can use the built in Nullable<T> class which wraps value types such that you can set them to null, check if it HasValue and get its actual Value. (Those are both methods on the Nullable<T> objects.

name = "";
Nullable<Color> color = null; //This will work.

There is also a shortcut you can use:

Color? color = null;

That is the same as Nullable<Color>;


I'm assuming c++ here. If you're using c#, the answer is probably the same, but the syntax will be a bit different. The enum is a set of int values. It's not an object, so you shouldn't be setting it to null. Setting something to null means you are pointing a pointer to an object to address zero. You can't really do that with an int. What you want to do with an int is to set it to a value you wouldn't normally have it at so that you can tel if it's a good value or not. So, set your colour to -1

Color color = -1;

Or, you can start your enum at 1 and set it to zero. If you set the colour to zero as it is right now, you will be setting it to "red" because red is zero in your enum.

So,

enum Color {
red =1
blue,
green
}
//red is 1, blue is 2, green is 3
Color mycolour = 0;

참고URL : https://stackoverflow.com/questions/4337193/how-to-set-enum-to-null

반응형