我有一组包含有关它们的信息的项目。这些项目是由我这个程序员定义的,用户永远不需要更改它们,它们永远不需要根据配置进行更改,而且它们唯一可能更改的时间是在我的应用程序的 future 版本中。我事先知道应该有多少这些项目,以及它们的确切数据是什么。
枚举是一种很棒的编程结构,它让我可以预定义一组在我的应用程序中可用的键,并将它们分组在一个逻辑类型下。
我现在需要的是一个结构,让我可以预定义一组附加了额外信息的键。
例子:
这是一个标准枚举:
public enum PossibleKeys
{
Key1,
Key2,
Key3
}
这是我需要的枚举:
public enum PossibleItems
{
Item1
{
Name = "My first item",
Description = "The first of my possible items."
},
Item2
{
Name = "My second item",
Description = "The second of my possible items."
},
Item3
{
Name = "My third item",
Description = "The third of my possible items."
}
}
我知道这种枚举不存在。我要问的是:在 C# 中,我如何硬编码一组预定义的项目,这些项目的数据是在代码中设置的?执行此操作的最佳方法是什么?
编辑:我不一定想要一个使用枚举的解决方案,只是一个允许我拥有这种行为的解决方案,即了解我的应用程序中所有可能的项目,以及他们每个人拥有的信息。
编辑 2:能够在运行时获取所有现有项目对我来说很重要。因此,需要能够查询所有项目并迭代它们。就像我可以使用枚举一样。
如果它纯粹是为了描述,您可以使用内置的 DescriptionAttribute
,如其他一些答案中所述。但是,如果您需要属性无法提供的功能,您可以使用某种元数据对象创建查找。
像这样:
public enum PossibleKeys
{
Key1,
Key2,
Key3
}
public class KeyMetadata
{
public PossibleKeys Id { get; set; }
public string Description { get; set; }
public SomeOtherClass SomethingAttributesCantHandle { get; set; }
}
private static readonly IReadOnlyDictionary<PossibleKeys, KeyMetadata> KeyMetadataLookup;
static EnumContainerClass()
{
Dictionary<PossibleKeys, KeyMetadata> metadata = new Dictionary<PossibleKeys, KeyMetadata>();
metadata.Add(PossibleKeys.Key1, new KeyMetadata { Id = PossibleKeys.Key1, Description = "First Item" });
metadata.Add(PossibleKeys.Key2, new KeyMetadata { Id = PossibleKeys.Key2, Description = "Second Item" });
metadata.Add(PossibleKeys.Key3, new KeyMetadata { Id = PossibleKeys.Key3, Description = "Third Item" });
KeyMetadataLookup = new ReadOnlyDictionary<PossibleKeys, KeyMetadata>(metadata);
}
然后检索:
KeyMetadataLookup[PossibleKeys.Key1].Description
请注意,只有在某些属性无法处理的情况下,我才会使用它。如果都是原始类型,您也可以简单地制作自己的自定义属性。您不仅限于内置的。
您自己的自定义属性最终会像这样:
[System.AttributeUsage(System.AttributeTargets.Field)]
public class CustomDataAttribute : System.Attribute
{
public string Name { get; set; }
public string Description { get; set; }
}
然后在使用:
public enum PossibleItems
{
[CustomData(Name = "My first item", Description = "The first of my possible items.")]
Item1,
[CustomData(Name = "My second item", Description = "The second of my possible items.")]
Item2,
[CustomData(Name = "My third item", Description = "The third of my possible items.")]
Item3
}
我是一名优秀的程序员,十分优秀!