Pourquoi ça ne marche pas?
Vous pouvez créer votre propre attribut par inherting de Attribute
public class EnumInformation: Attribute
{
public string LongDescription { get; set; }
public string ShortDescription { get; set; }
}
public static string GetLongDescription(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
EnumInformation [] attribs = fieldInfo.GetCustomAttributes(
typeof(EnumInformation), false) as EnumInformation [];
// Return the first if there was a match.
return attribs != null && attribs.Length > 0 ? attribs[0].LongDescription : null;
}
public static string GetShortDescription(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
EnumInformation [] attribs = fieldInfo.GetCustomAttributes(
typeof(EnumInformation), false) as EnumInformation [];
// Return the first if there was a match.
return attribs != null && attribs.Length > 0 ? attribs[0].ShortDescription : null;
}
Votre Enum ressemblerait à ceci
public enum MyEnum
{
[EnumInformation(LongDescription="This is the Number 1", ShortDescription= "1")]
One,
[EnumInformation(LongDescription = "This is the Number Two", ShortDescription = "2")]
Two
}
Vous pouvez l'utiliser de cette façon
MyEnum test1 = MyEnum.One;
Console.WriteLine("test1.GetLongDescription = {0}", test1.GetLongDescription());
Console.WriteLine("test1.GetShortDescription = {0}", test1.GetShortDescription());
Il produit
test1.GetLongDescription = Ceci est le numéro 1
test1.GetShortDescription = 1
Vous pouvez réellement ajouter des propriétés à l'attribut d'avoir toutes sortes d'informations. Ensuite, vous pourriez soutenir la localisation que vous recherchez.
Pour plus de clarté, pouvez-vous poster un exemple d'énumération comme celle que vous aimeriez utiliser? – HitLikeAHammer
Pourquoi vos noms d'énumération sont-ils si longs? Typiquement, une énumération est simplement un moyen mnémotechnique pour le programmeur de se référer à des valeurs numériques dans le code PAS un moyen de stocker des valeurs de chaîne. En général, la récupération des noms est sensibile lorsque vous donnez à un utilisateur la possibilité de sélectionner une valeur donnée à partir de l'énumération ou à des fins d'affichage. – Achilles
@Achilles: Habituellement l'enum aura un texte descriptif pour l'accompagner, d'où la raison pour les noms longs. – NotMe