如何将枚举设置为空

发布于 2024-10-05 15:14:55 字数 1575 浏览 1 评论 0原文

我有一个枚举

string name;

public enum Color
{
  Red,
  Green,
  Yellow
}

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

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

编辑: 我的错,我没有正确解释它。但所有与可为空相关的答案都是完美的。我的情况是,如果我在一个具有其他元素(如名称等)的类中获取/设置枚举,会怎样。在页面加载时,我初始化该类并尝试将值默认为 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 方法一起使用。我只需要添加“?”在声明私有枚举变量期间和在 get/set 方法中的 EnumTest 类中:

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

}

感谢所有人的可爱建议。

I have an enum

string name;

public enum Color
{
  Red,
  Green,
  Yellow
}

How to set it to NULL on load.

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

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

}

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

}

Thanks all for the lovely suggestions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

墟烟 2024-10-12 15:14:55

您可以使用“?”可空类型的运算符。

public Color? myColor = null;

或者使用枚举的标准做法,将枚举中的第一个值(也称为 0)作为默认值,从而不能为空。例如,在颜色无的情况下。

public Color myColor = Color.None;

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

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;
冬天旳寂寞 2024-10-12 15:14:55

如果这是 C#,它将不起作用:枚举是值类型,并且不能为 null

正常的选项是添加 None 成员:

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

Color color = Color.None;

...或使用 Nullable

Color? color = null;

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;
烛影斜 2024-10-12 15:14:55

让你的变量可以为空。喜欢:

Color? color = null;

Nullable<Color> color = null;

Make your variable nullable. Like:

Color? color = null;

or

Nullable<Color> color = null;
迎风吟唱 2024-10-12 15:14:55

枚举是 C# 中的“值”类型(意味着枚举存储为任何值,而不是存储值本身的内存位置的引用)。您不能将值类型设置为 null(因为 null 仅用于引用类型)。

也就是说,您可以使用内置的 Nullable 类来包装值类型,以便您可以将它们设置为 null,检查它是否 HasValue 并获取其实际的 <代码>值。 (这些都是 Nullable 对象上的方法。

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

您还可以使用一个快捷方式:

Color? color = null;

Nullable 相同;

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

心安伴我暖 2024-10-12 15:14:55

使用 Nullable enum 作为类/方法变量和类属性时的一些观察和陷阱:


C# v7.3 (在 .NET v4.7.2VS2019 上测试),

这有效:

Color? color = null; // works

但这不起作用:

Color? color = condition ? Color.Red : null;

// Error CS8370 
// Feature 'target-typed conditional expression' is not available in C# 7.3.  
// Please use language version 9.0 or greater.

修复方法是类型转换 null:

Color? color = condition ? Color.Red : (Color?)null; // works

此外,命名变量 Color,即与类型完全相同的情况,仅当类型不可为 Nullable 时才有效

Color Color = condition ? Color.Red : Color.None; // works fine!

但是在以下情况下会严重失败类型可为 Nullable :

Color? Color = condition ? Color.Red : (Color?)null;

// Error CS0165 Use of unassigned local variable 'Color'
// Error CS1061 'Color?' does not contain a definition for 'Red' 
// and no accessible extension method 'Red' accepting a first argument of type 'Color?' 
// could be found (are you missing a using directive or an assembly reference?)

解决方法是使用带有命名空间的类型的完全限定名称:

Color? Color = condition ? MyEnums.Color.Red : (Color?)null; // works now

但最好坚持变量小写命名的标准做法:

Color? color = condition ? Color.Red : (Color?)null; // works now

对于 class 级别的属性可以看到类似的问题:

class Program {
    Color? Color => Condition ? Color.Red : (Color?)null;
}

// Error CS1061 'Color?' does not contain a definition for 'Red' 
// and no accessible extension method 'Red' accepting a first argument of type 'Color?' 
// could be found (are you missing a using directive or an assembly reference?)

同样,修复方法是完全限定类型:

Color? Color => Condition ? MyEnums.Color.Red : (Color?)null; // works now

Some observations and gotchas when working with Nullable enum as class/method variables, and class properties:


In C# v7.3 (tested on .NET v4.7.2 with VS2019),

this works:

Color? color = null; // works

but this doesn't:

Color? color = condition ? Color.Red : null;

// Error CS8370 
// Feature 'target-typed conditional expression' is not available in C# 7.3.  
// Please use language version 9.0 or greater.

The fix is to type-cast null:

Color? color = condition ? Color.Red : (Color?)null; // works

Furthermore, naming the variable Color, i.e. exactly the same case as the type, works only when the type is non-Nullable:

Color Color = condition ? Color.Red : Color.None; // works fine!

But fails miserably when the type is Nullable:

Color? Color = condition ? Color.Red : (Color?)null;

// Error CS0165 Use of unassigned local variable 'Color'
// Error CS1061 'Color?' does not contain a definition for 'Red' 
// and no accessible extension method 'Red' accepting a first argument of type 'Color?' 
// could be found (are you missing a using directive or an assembly reference?)

The fix is to use the fully-qualified name of the type with the namespace:

Color? Color = condition ? MyEnums.Color.Red : (Color?)null; // works now

But it is best to stick to standard practice of lower-case naming for the variable:

Color? color = condition ? Color.Red : (Color?)null; // works now

A similar problem can be seen for a property at class-level:

class Program {
    Color? Color => Condition ? Color.Red : (Color?)null;
}

// Error CS1061 'Color?' does not contain a definition for 'Red' 
// and no accessible extension method 'Red' accepting a first argument of type 'Color?' 
// could be found (are you missing a using directive or an assembly reference?)

Again, the fix is to fully-qualify the type:

Color? Color => Condition ? MyEnums.Color.Red : (Color?)null; // works now
染墨丶若流云 2024-10-12 15:14:55

我假设这里是c++。如果您使用 C#,答案可能是相同的,但语法会有点不同。
枚举是一组 int 值。它不是一个对象,因此您不应将其设置为 null。将某些内容设置为 null 意味着您将指向对象的指针指向零地址。你不能用 int 来做到这一点。您想要对 int 执行的操作是将其设置为您通常不会使用的值,以便您可以判断它是否是一个好的值。
因此,将颜色设置为 -1

Color color = -1;

或者,您可以从 1 开始枚举并将其设置为零。如果您将颜色设置为零,就像现在一样,您将把它设置为“红色”,因为红色在您的枚举中为零。

所以,

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

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;
她如夕阳 2024-10-12 15:14:55
Color? color = null;

或者您可以使用

Color? color = new Color?();

分配 null 不起作用的示例,

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

因此您可以使用:

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 
Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 
萌︼了一个春 2024-10-12 15:14:55

将值 0 显式分配给 None 不是更好吗?
持续的?为什么?

因为默认的enum值等于0,如果您调用default(Color),它将打印None

因为它位于第一个位置,所以将文字值 0 分配给任何其他常量都会更改该行为,并且更改出现顺序也会更改 default(Color) 的输出 (https://stackoverflow.com/a/4967673/8611327

would it not be better to explicitly assign value 0 to None
constant? Why?

Because default enum value is equal to 0, if You would call default(Color) it would print None.

Because it is at first position, assigning literal value 0 to any other constant would change that behaviour, also changing order of occurrence would change output of default(Color) (https://stackoverflow.com/a/4967673/8611327)

魂牵梦绕锁你心扉 2024-10-12 15:14:55

样品是这样完成的

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

  Color colors = Colors.null;

It is done so sample like this

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

  Color colors = Colors.null;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文