基本上我想定义一个带小数值的枚举,但这是不可能的。另一种选择是:
public static class EstadoRestriccion
{
public const decimal Valur1 = 0;
public const decimal Value2 = 0.5M;
public const decimal Value3 = 1;
};
但是我需要在组合框中添加这些常量,其中显示的选项应该是常量的名称,SelectedItem
应该返回值(0,0.5M,1)或类似这些。我知道这是可能的,但它很难看。
有了枚举,我可以轻松地做到这一点:comboBox.DataSource = Enum.GetValues(typeof(MyEnum));
根据我的要求模拟枚举的最佳方法是什么?
答案 0 :(得分:5)
字典可能是个不错的选择。
Dictionary<string,decimal>
可能是一个很好的候选人 - 让你命名这些值。
var values = new Dictionary<string,decimal>();
values.Add("Value1", 0m);
values.Add("Value2", 0.5m);
values.Add("Value3", 1m);
这可以包装在一个类中,因此您只能通过索引而不是整个Dictionary<TKey,TValue>
接口公开getter。
答案 1 :(得分:2)
static readonly
十进制数组怎么样?
public static readonly decimal[] myValues = new[] {0, 0.5M, 1};
答案 2 :(得分:2)
你可以稍微改变你的课程:
public class EstadoRestriccion
{
public static readonly EstadoRestriccion Value1 = new EstadoRestriccion("Value1", 0);
public static readonly EstadoRestriccion Value2 = new EstadoRestriccion("Value2", 0.5M);
public static readonly EstadoRestriccion Value3 = new EstadoRestriccion("Value3", 1);
private static readonly EstadoRestriccion[] values = new EstadoRestriccion[] { Value1, Value2, Value3 };
private string name;
private decimal value;
private EstadoRestriccion(string name, decimal value)
{
this.name = name;
this.value = value;
}
public static EstadoRestriccion[] GetValues()
{
return values;
}
public override string ToString()
{
return this.name;
}
};
一些decimal
转化和/或将value
更改为公共财产。
答案 3 :(得分:1)
没有办法简单。 enum
仅接受整数值。你输入的代码片段很好。
const decimal
和static readonly decimal
之间存在细微差别。首先是直接评估;编译器将名称替换为其值。相反,readonly
强制代码每次引用字段并从中获取值。您可以观察为readonly
使用引用类型而const
不能使用的原因(期望字符串)。