java 枚举型 默认值,c# - 选择Enum类型的默认值而不必更改值

c# - 选择Enum类型的默认值而不必更改值

在C#中,是否可以使用属性修饰Enum类型或执行其他操作来指定默认值应该是什么,而不更改值? 无论出于何种原因,所需的数字可能都是一成不变的,并且仍然可以控制默认值。

enum Orientation

{

None = -1,

North = 0,

East = 1,

South = 2,

West = 3

}

Orientation o; // Is 'North' by default.

xyz asked 2019-03-22T10:15:50Z

12个解决方案

293 votes

enum(实际上是任何值类型)的默认值为0 - 即使它不是enum的有效值。它无法更改。

James Curran answered 2019-03-22T10:16:01Z

59 votes

任何枚举的默认值为零。 因此,如果要将一个枚举器设置为默认值,则将其设置为零,将所有其他枚举器设置为非零(如果有多个枚举器,则第一个枚举值为零的第一个枚举器将是该枚举的默认值 值为零)。

enum Orientation

{

None = 0, //default value since it has the value '0'

North = 1,

East = 2,

South = 3,

West = 4

}

Orientation o; // initialized to 'None'

如果您的枚举器不需要显式值,那么只需确保第一个枚举器是您想要成为默认枚举器的枚举器,因为“默认情况下,第一个枚举器的值为0,每个连续枚举器的值增加为1.” (C#参考)

enum Orientation

{

None, //default value since it is the first enumerator

North,

East,

South,

West

}

Orientation o; // initialized to 'None'

Emperor XLII answered 2019-03-22T10:16:34Z

31 votes

如果零不能作为正确的默认值,则可以使用组件模型为枚举定义变通方法:

[DefaultValue(None)]

public enum Orientation

{

None = -1,

North = 0,

East = 1,

South = 2,

West = 3

}

public static class Utilities

{

public static TEnum GetDefaultValue() where TEnum : struct

{

Type t = typeof(TEnum);

DefaultValueAttribute[] attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);

if (attributes != null &&

attributes.Length > 0)

{

return (TEnum)attributes[0].Value;

}

else

{

return default(TEnum);

}

}

}

然后你可以打电话:

Orientation o = Utilities.GetDefaultValue();

System.Diagnostics.Debug.Print(o.ToString());

注意:您需要在文件顶部包含以下行:

using System.ComponentModel;

这不会更改枚举的实际C#语言默认值,但会提供一种指示(并获取)所需默认值的方法。

David answered 2019-03-22T10:17:21Z

16 votes

枚举的默认值是枚举等于零。 我不相信这可以通过属性或其他方式改变。

(MSDN说:“枚举E的默认值是表达式(E)0产生的值。”)

Joe answered 2019-03-22T10:17:53Z

9 votes

你不能,但如果你愿意,你可以做一些技巧。:)

public struct Orientation

{

...

public static Orientation None = -1;

public static Orientation North = 0;

public static Orientation East = 1;

public static Orientation South = 2;

public static Orientation West = 3;

}

这个结构的用法是简单的枚举。

您可以在其中默认创建p.a == Orientation.East(或任何您想要的值)

要使用技巧本身,您需要通过代码转换为int。

有实施:

#region ConvertingToEnum

private int val;

static Dictionary dict = null;

public Orientation(int val)

{

this.val = val;

}

public static implicit operator Orientation(int value)

{

return new Orientation(value - 1);

}

public static bool operator ==(Orientation a, Orientation b)

{

return a.val == b.val;

}

public static bool operator !=(Orientation a, Orientation b)

{

return a.val != b.val;

}

public override string ToString()

{

if (dict == null)

InitializeDict();

if (dict.ContainsKey(val))

return dict[val];

return val.ToString();

}

private void InitializeDict()

{

dict = new Dictionary();

foreach (var fields in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))

{

dict.Add(((Orientation)fields.GetValue(null)).val, fields.Name);

}

}

#endregion

Avram answered 2019-03-22T10:19:06Z

6 votes

另一种可能有用的方法 - 使用某种“别名”。例如:

public enum Status

{

New = 10,

Old = 20,

Actual = 30,

// Use Status.Default to specify default status in your code.

Default = New

}

Dmitry Pavlov answered 2019-03-22T10:20:08Z

6 votes

实际上,enum的默认值是enum中的第一个元素,其值为0。

例如:

public enum Animals

{

Cat,

Dog,

Pony = 0,

}

//its value will actually be Cat not Pony unless you assign a non zero value to Cat.

Animals animal;

Cian answered 2019-03-22T10:21:26Z

3 votes

The default value of enum is the enummember equal to 0 or the first element(if value is not specified) ...但我在我的项目中使用枚举遇到了严重的问题,并通过以下方式做了一些事情......我的需求如何与班级相关...

class CDDtype

{

public int Id { get; set; }

public DDType DDType { get; set; }

public CDDtype()

{

DDType = DDType.None;

}

}

[DefaultValue(None)]

public enum DDType

{

None = -1,

ON = 0,

FC = 1,

NC = 2,

CC = 3

}

并得到预期的结果

CDDtype d1= new CDDtype();

CDDtype d2 = new CDDtype { Id = 50 };

Console.Write(d1.DDType);//None

Console.Write(d2.DDType);//None

现在如果价值来自DB ......如果在这种情况下好了...在下面的函数中传递值,它会将值转换为枚举...下面的函数处理各种场景并且它是通用的......并且相信我是 非常快 ..... :)

public static T ToEnum(this object value)

{

//Checking value is null or DBNull

if (!value.IsNull())

{

return (T)Enum.Parse(typeof(T), value.ToStringX());

}

//Returanable object

object ValueToReturn = null;

//First checking whether any 'DefaultValueAttribute' is present or not

var DefaultAtt = (from a in typeof(T).CustomAttributes

where a.AttributeType == typeof(DefaultValueAttribute)

select a).FirstOrNull();

//If DefaultAttributeValue is present

if ((!DefaultAtt.IsNull()) && (DefaultAtt.ConstructorArguments.Count == 1))

{

ValueToReturn = DefaultAtt.ConstructorArguments[0].Value;

}

//If still no value found

if (ValueToReturn.IsNull())

{

//Trying to get the very first property of that enum

Array Values = Enum.GetValues(typeof(T));

//getting very first member of this enum

if (Values.Length > 0)

{

ValueToReturn = Values.GetValue(0);

}

}

//If any result found

if (!ValueToReturn.IsNull())

{

return (T)Enum.Parse(typeof(T), ValueToReturn.ToStringX());

}

return default(T);

}

Moumit answered 2019-03-22T10:26:10Z

2 votes

默认值是定义中的第一个。 例如:

public enum MyEnum{His,Hers,Mine,Theirs}

Enum.GetValues(typeOf(MyEnum)).GetValue(0);

这将返回His

Tony Hopkinson answered 2019-03-22T10:26:44Z

1 votes

枚举类型的默认值为0:

“默认情况下,第一个枚举数的值为0,值为每个连续的调查员增加1.“

“值类型枚举具有由表达式(E)0生成的值,其中E是枚举标识符“。

您可以在此处查看C#enum的文档,以及此处的C#默认值表文档。

acoelhosantos answered 2019-03-22T10:27:38Z

1 votes

如果将Default枚举定义为具有最小值的枚举,则可以使用:

public enum MyEnum { His = -1, Hers = -2, Mine = -4, Theirs = -3 }

var firstEnum = ((MyEnum[])Enum.GetValues(typeof(MyEnum)))[0];

firstEnum == Mine.

这并不假设枚举值为零。

Tal Segal answered 2019-03-22T10:28:14Z

-5 votes

[DefaultValue(None)]

public enum Orientation

{

None = -1,

North = 0,

East = 1,

South = 2,

West = 3

}

然后在您可以使用的代码中

public Orientation GetDefaultOrientation()

{

return default(Orientation);

}

Ruslan Urban answered 2019-03-22T10:28:41Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值