出于通常的原因,我需要在我的应用程序中使用一些常量。
我考虑过的方法:
1) 声明一个枚举:
public enum myOptions
{
MyOption1 = 72,
MyOption2 = 31,
MyOption3 = 44
}
虽然这很适合编程,而且我可以将枚举直接绑定(bind)到 DDL,但是当用户看到时,枚举“名称”很难看 - 用户将看到“MyOption1”,我希望他们看到“我的选择#1”。
2) 使用列表:
public static List<KeyValuePair<int, string>> myOptions = new List<KeyValuePair<int, string>>
{
new KeyValuePair<int, string>(77, "My Option #1"),
new KeyValuePair<int, string>(31, "My Option #2"),
new KeyValuePair<int, string>(44, "My Option #3")
}
因此,虽然这很好地绑定(bind)到 DDL,为我提供了一个漂亮的显示值和一个整数返回值,但我没有任何东西可以用来测试我的返回值。所以,例如:
if (selectedOption=????) //I'd have to hardcode the Key or Value I want to test for.
3) 我可以构建漂亮的全局/常量程序集:
static myOptions
{
public static KeyValuePair<int, string> MyOption1 = new new KeyValuePair<int, string>(77, "My Option #1");
public static KeyValuePair<int, string> MyOption2 = new new KeyValuePair<int, string>(31, "My Option #2");
public static KeyValuePair<int, string> MyOption3 = new new KeyValuePair<int, string>(44, "My Option #3");
}
这给了我很好的显示名称,很适合编码,但据我所知,我无法轻松地将它绑定(bind)到 DDL(我必须手动编码)。
有没有人有一种优雅的方法来创建易于绑定(bind)到 DDL 的常量,我可以在其中有一个漂亮的显示名称?
现在我唯一能想到的就是同时构建 Enum 和 List,这看起来很烦人。
请您参考如下方法:
我总是倾向于修饰枚举值:
public enum myOptions
{
[Description("My Option #1")]
MyOption1 = 72,
[Description("My Option #2")]
MyOption2 = 31,
[Description("My Option #3")]
MyOption3 = 44
}
或者更好的是,您可以创建一个自定义属性来绑定(bind)到资源文件或配置设置,这样就可以在不重新编译的情况下更改此数据
public enum myOptions
{
[Custom("MyOption1Key")]
MyOption1 = 72,
[Custom("MyOption2Key")]
MyOption2 = 31,
[Custom("MyOption3Key")]
MyOption3 = 44
}
更新以从枚举中提取属性
public static T GetAttribute<T>(this Enum e) where T : Attribute
{
FieldInfo fieldInfo = e.GetType().GetField(e.ToString());
T[] attribs = fieldInfo.GetCustomAttributes(typeof(T), false) as T[];
return attribs.Length > 0 ? attribs[0] : null;
}
