gpt4 book ai didi

C# 枚举类型安全

转载 作者:太空狗 更新时间:2023-10-30 01:02:47 25 4
gpt4 key购买 nike

有没有办法强制 C# 枚举只接受几个明确命名的常量之一,或者是否有其他功能可以做到? C# 引用有这个事后的想法:

It is possible to assign any arbitrary integer value to an enum type. However, you should not do this because the implicit expectation is that an enum variable will only hold one of the values defined by the enum. To assign an arbitrary value to a variable of an enumeration type is to introduce a high risk for errors.

(一种新语言的设计允许这种草率。这让我感到困惑。)

最佳答案

据我所知,您无法阻止 C# 允许枚举和整数之间的转换。

作为变通方法,您可以改为使用具有受限实例化的自定义类型。用法看起来很相似,但您还将有机会为此类型定义方法和运算符。

假设你有这个枚举:

enum DayOfWeek
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

您可以使用密封类代替它。优点是您可以免费进行比较(因为在这种情况下,值比较和引用比较是等效的)。缺点是(与 C# 中的所有引用类型一样),它可以为 null。

sealed class DayOfWeek
{
public static readonly DayOfWeek Monday = new DayOfWeek(0);
public static readonly DayOfWeek Tuesday = new DayOfWeek(1);
public static readonly DayOfWeek Wednesday = new DayOfWeek(2);
public static readonly DayOfWeek Thursday = new DayOfWeek(3);
public static readonly DayOfWeek Friday = new DayOfWeek(4);
public static readonly DayOfWeek Saturday = new DayOfWeek(5);
public static readonly DayOfWeek Sunday = new DayOfWeek(6);

private readonly int _value;

private DayOfWeek(int value)
{
_value = value;
}
}

或者您可以使用结构。优点是它不可为空,因此它更类似于枚举。缺点是你必须手动实现比较代码:

struct DayOfWeek
{
public static readonly DayOfWeek Monday = new DayOfWeek(0);
public static readonly DayOfWeek Tuesday = new DayOfWeek(1);
public static readonly DayOfWeek Wednesday = new DayOfWeek(2);
public static readonly DayOfWeek Thursday = new DayOfWeek(3);
public static readonly DayOfWeek Friday = new DayOfWeek(4);
public static readonly DayOfWeek Saturday = new DayOfWeek(5);
public static readonly DayOfWeek Sunday = new DayOfWeek(6);

private readonly int _value;

private DayOfWeek(int value)
{
_value = value;
}

public bool Equals(DayOfWeek other)
{
return _value == other._value;
}

public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is DayOfWeek && Equals((DayOfWeek)obj);
}

public override int GetHashCode()
{
return _value;
}

public static bool operator ==(DayOfWeek op1, DayOfWeek op2)
{
return op1.Equals(op2);
}

public static bool operator !=(DayOfWeek op1, DayOfWeek op2)
{
return !(op1 == op2);
}
}

关于C# 枚举类型安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32418634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com