У меня есть перечисление, определенное как
enum Tile { Empty, White, Black };
Но предположим, что, записанные на консоль,
Console.Write(Tile.White);
Я хочу, чтобы он печатал
W
Или любое другое значение, я мог бы использовать switch
для этого, но есть ли лучший способ? Возможно, используя атрибуты?
Вот что я имею в виду. Написав что-то вроде этого,
[AttributeUsage(AttributeTargets.Field)]
public class ReprAttribute : Attribute
{
public string Representation;
public ReprAttribute(string representation)
{
this.Representation = representation;
}
public override string ToString()
{
return this.Representation;
}
}
enum Tile {
[Repr(".")]
Empty,
[Repr("W")]
White,
[Repr("B")]
Black
};
// ...
Console.Write(Tile.Empty)
Выведет
.
Конечно, что override string ToString()
не делал то, что я надеялся сделать (он все же выводит "Empty" вместо этого.
В этой статье это очень хорошо выглядит: http://blogs.msdn.com/b/abhinaba/archive/2005/10/20/c-enum-and-overriding-tostring-on-it.aspx