如果纯粹是为了描述,您可以使用内置的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
}