gpt4 book ai didi

c# - 我可以在尝试使用或返回枚举值时避免强制转换它吗?

转载 作者:IT王子 更新时间:2023-10-29 04:14:07 25 4
gpt4 key购买 nike

如果我有以下枚举:

public enum ReturnValue{
Success = 0,
FailReason1 = 1,
FailReason2 = 2
//Etc...
}

我可以在返回时避免转换吗,像这样:

public static int main(string[] args){
return (int)ReturnValue.Success;
}

如果不是,为什么默认情况下不将枚举值视为 int?

最佳答案

枚举应该是类型安全的。我认为他们并没有让它们隐式转换以阻止其他用途。尽管框架允许您为它们分配一个常量值,但您应该重新考虑您的意图。如果您主要使用枚举来存储常量值,请考虑使用静态类:

public static class ReturnValue
{
public const int Success = 0;
public const int FailReason1 = 1;
public const int FailReason2 = 2;
//Etc...
}

这让你可以做到这一点。

public static int main(string[] args){
return ReturnValue.Success;
}

编辑

当您确实想要为枚举提供值时,就是您想要组合它们的时候。请参阅以下示例:

[Flags] // indicates bitwise operations occur on this enum
public enum DaysOfWeek : byte // byte type to limit size
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
Weekend = Sunday | Saturday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}

然后可以使用按位数学来使用此枚举。有关某些应用程序,请参见下面的示例。

public static class DaysOfWeekEvaluator
{
public static bool IsWeekends(DaysOfWeek days)
{
return (days & DaysOfWeek.Weekend) == DaysOfWeek.Weekend;
}

public static bool IsAllWeekdays(DaysOfWeek days)
{
return (days & DaysOfWeek.Weekdays) == DaysOfWeek.Weekdays;
}

public static bool HasWeekdays(DaysOfWeek days)
{
return ((int) (days & DaysOfWeek.Weekdays)) > 0;
}

public static bool HasWeekendDays(DaysOfWeek days)
{
return ((int) (days & DaysOfWeek.Weekend)) > 0;
}
}

关于c# - 我可以在尝试使用或返回枚举值时避免强制转换它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/577946/

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