如何在 Enum 中添加和使用 null 值?

4 .net c# enums

请参阅下面的枚举包含两个成员:测试和生产

public enum OTA_HotelInvCountNotifRQTarget
{      
    Test,      
    Production,
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找在上述枚举中添加和使用 Null 值的方法,代码如下:

inv.Target = OTA_HotelInvCountNotifRQTarget.Null; // Not allowed
Run Code Online (Sandbox Code Playgroud)

更新: 我不想NULL在上面的枚举中添加额外的内容,我想使其动态化,因为上面的枚举是自动生成的。并且应该保持不变。

有没有办法在方法本身中实现这一点,即无需在枚举中创建任何Class或添加额外的Enum值?喜欢 :inv.Target = OTA_HotelInvCountNotifRQTarget.Null;

我怎样才能做到这一点?

Gil*_*een 5

an 的下划线值enumint不能分配给 的值null

如果您仍想这样做:

  1. 添加Null为枚举的选项:

    public enum OTA_HotelInvCountNotifRQTarget
    {
        Null,
        Test,
        Production
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 让你的目标为 Nullable 类型:

    Nullable<OTA_HotelInvCountNotifRQTarget> t = null;
    
    //Or in a cleaner way:
    OTA_HotelInvCountNotifRQTarget? t = null;
    
    //And in your class:
    public class YourType
    {
        public OTA_HotelInvCountNotifRQTarget? Target { get; set; }
    }
    
    Run Code Online (Sandbox Code Playgroud)