简体   繁体   English

如何将枚举设置为 null

[英]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.我的情况是如果,我已经获取/设置了 class 中的枚举以及名称等其他元素。在页面加载时,我初始化 class 并尝试将值默认为 Z37A6259CC0C1DAE299A7866489DFFBD0 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 class 在声明私有枚举变量期间和在 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.感谢所有可爱的建议。

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.或者通过将枚举中的第一个值(又名 0)作为默认值来使用不能为空的枚举的标准做法。 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 .如果这是 C#,它将不起作用:枚举是值类型,不能为null

The normal options are to add a None member:正常的选项是添加一个None成员:

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

Color color = Color.None;

...or to use Nullable : ...或使用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).枚举是 C# 中的“值”类型(意味着枚举存储为任何值,而不是作为对存储值本身的内存位置的引用)。 You can't set value types to null (since null is used for reference types only).您不能将值类型设置为 null(因为 null 仅用于引用类型)。

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 .话虽如此,您可以使用内置的Nullable<T>类包装值类型,以便您可以将它们设置为 null,检查它是否HasValue并获取其实际Value (Those are both methods on the Nullable<T> objects. (这些都是Nullable<T>对象上的方法。

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> ;这与Nullable<Color>相同;

Some observations and gotchas when working with Nullable enum as class/method variables, and class properties:使用Nullable enum作为类/方法变量和 class 属性时的一些观察和陷阱


In C# v7.3 (tested on .NET v4.7.2 with VS2019 ),C# v7.3中(在.NET v4.7.2VS2019上测试),

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 :修复是对null进行类型转换:

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

Furthermore, naming the variable Color , ie exactly the same case as the type, works only when the type is non-Nullable :此外,命名变量Color ,即与类型完全相同的大小写,仅在类型为 non-Nullable 时才有效

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

But fails miserably when the type is Nullable :但是当类型为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级别的属性,可以看到类似的问题:

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

I'm assuming c++ here.我在这里假设是 C++。 If you're using c#, the answer is probably the same, but the syntax will be a bit different.如果您使用的是 c#,答案可能是相同的,但语法会有所不同。 The enum is a set of int values.枚举是一组 int 值。 It's not an object, so you shouldn't be setting it to null.它不是一个对象,所以你不应该将它设置为 null。 Setting something to null means you are pointing a pointer to an object to address zero.将某些内容设置为 null 意味着您指向一个指向零地址的对象的指针。 You can't really do that with an int.你真的不能用 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.你想对 int 做的是将它设置为一个你通常不会拥有的值,这样你就可以知道它是否是一个好的值。 So, set your colour to -1因此,将颜色设置为 -1

Color color = -1;

Or, you can start your enum at 1 and set it to zero.或者,您可以从 1 开始枚举并将其设置为零。 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;

would it not be better to explicitly assign value 0 to None constant?将值 0 显式分配给None常量不是更好吗? Why?为什么?

Because default enum value is equal to 0, if You would call default(Color) it would print None .因为默认enum值等于 0,如果您调用default(Color)它将打印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 )因为它位于第一个位置,将文字值 0 分配给任何其他常量会改变这种行为,改变出现顺序也会改变default(Color)输出( https://stackoverflow.com/a/4967673/8611327

Color? color = null;

or you can use或者你可以使用

Color? color = new Color?();

example where assigning null wont work分配 null 不起作用的示例

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?(); 

It is done so sample like this这样做是这样的样本

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

  Color colors = Colors.null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM