在c#中,是否有可能用属性装饰Enum类型或做一些其他事情来指定默认值应该是什么,而不改变值?由于某种原因,所需的数字可能是固定不变的,而且仍然可以控制默认值是很方便的。
enum Orientation
{
None = -1,
North = 0,
East = 1,
South = 2,
West = 3
}
Orientation o; // Is 'North' by default.
在c#中,是否有可能用属性装饰Enum类型或做一些其他事情来指定默认值应该是什么,而不改变值?由于某种原因,所需的数字可能是固定不变的,而且仍然可以控制默认值是很方便的。
enum Orientation
{
None = -1,
North = 0,
East = 1,
South = 2,
West = 3
}
Orientation o; // Is 'North' by default.
当前回答
enum Orientations
{
None, North, East, South, West
}
private Orientations? _orientation { get; set; }
public Orientations? Orientation
{
get
{
return _orientation ?? Orientations.None;
}
set
{
_orientation = value;
}
}
如果将属性设置为null,则会返回朝向。没有得到。 属性_orientation默认为空。
其他回答
enum Orientations
{
None, North, East, South, West
}
private Orientations? _orientation { get; set; }
public Orientations? Orientation
{
get
{
return _orientation ?? Orientations.None;
}
set
{
_orientation = value;
}
}
如果将属性设置为null,则会返回朝向。没有得到。 属性_orientation默认为空。
实际上,枚举的默认值是枚举中第一个值为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;
如果0不是合适的默认值,你可以使用组件模型为枚举定义一个变通方法:
[DefaultValue(None)]
public enum Orientation
{
None = -1,
North = 0,
East = 1,
South = 2,
West = 3
}
public static class Utilities
{
public static TEnum GetDefaultValue<TEnum>() 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<Orientation>();
System.Diagnostics.Debug.Print(o.ToString());
注意:你需要在文件顶部包含以下一行:
using System.ComponentModel;
这不会改变枚举的实际c#语言默认值,但提供了一种方法来指示(并获得)所需的默认值。
枚举类型的默认值为0:
默认情况下,第一个枚举数的值为0,值为 每个连续的枚举数加1。” 值类型enum包含表达式(E)0产生的值,其中E是enum 标识符”。
你可以在这里查看c#枚举的文档和c#默认值表的文档。
默认值是定义中的第一个。例如:
public enum MyEnum{His,Hers,Mine,Theirs}
Enum.GetValues(typeOf(MyEnum)).GetValue(0);
这将返回他的