Подтвердить что ты не робот

Перечислить строку?

У меня есть перечисление, определенное как

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

4b9b3361

Ответ 1

Вы можете использовать атрибуты:

using System.ComponentModel;

public enum Tile
{
    [Description("E")]
    Empty,

    [Description("W")]
    White,

    [Description("B")]
    Black
}

И вспомогательный метод:

public static class ReflectionHelpers
{
    public static string GetCustomDescription(object objEnum)
    {
        var fi = objEnum.GetType().GetField(objEnum.ToString());
        var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return (attributes.Length > 0) ? attributes[0].Description : objEnum.ToString();
    }

    public static string Description(this Enum value)
    {
        return GetCustomDescription(value);
    }
}

Использование:

Console.Write(Tile.Description());

Ответ 2

Наивный неатрибутный способ:

public enum Tile {
    White = 'W',
    Black = 'B'
} 
//...
System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}", Tile.White.ToString(), (char)Tile.White));
//Prints out:
//White - W

Ответ 3

Вы можете использовать метод ToString():

Tile t = Tile.White;
Console.WriteLine(t.ToString()); // prints "White"
Console.WriteLine(t.ToString().SubString(0, 1)); // prints "W"

Ответ 4

Enum.GetName(typeof(Tile), enumvalue)

Это приведет к перечислению в виде строки.

Ответ 5

Вы можете использовать комбинацию Enum.GetName и Substring.

Что-то по строкам:

private string GetShortName(Tile t)
{
    return Enum.GetName(typeof(Tile), t).Substring(0, 1);
}

...

Console.WriteLine(GetShortName(Tile.White));

Ответ 6

Вы можете попробовать следующее:

private string GetFirstEnumLetter(Tile tile)
{
    if (tile.ToString().Length > 0)
    {
        return tile.ToString().Substring(0, 1);
    }

    return string.Empty;
}

И затем конвертируйте его каждый раз, когда вы хотите, вызывая:

Console.Write(GetFirstEnumLetter(Tile.White));

Надеюсь, что это поможет.

Ответ 7

В Java вы бы это сделали (написано это, прежде чем замечать, что это вопрос С#, извините! Но это может быть полезно кому-то...):

public enum Tile {

    Empty ( "." ), White ( "W" ), Black ( "B" ) ;

    private String abbr;

        //Note this is private
    private Tile ( String abbr ) {

        this.abbr = abbr;
    }

    public String getAbbr () {

        return abbr;
    }

        //The following is only necessary if you need to get an enum type for an abbreviation
    private static final Map<String, Tile> lookup = new HashMap<String, Tile>();

    static {
        for ( Tile t : EnumSet.allOf( Tile.class ) )
            lookup.put( t.getAbbr(), t );
    }

    public static Tile get ( String abbr ) {

        return lookup.get( abbr );
    }
}

public class TestTile {

public static void main ( String[] args ) {

    System.out.println(Tile.Black.getAbbr());
    System.out.println(Tile.White.getAbbr());
    System.out.println(Tile.Empty.getAbbr());

    System.out.println(Tile.get( "W" ));

}

}

Вывод:

В

Ш

.

Белый

Это дает вам двухсторонний перевод в перечисление и из него.

Вы не можете просто распечатать Tile.White и ожидать, что он напечатает что-то еще, поэтому вам нужно вызвать Tile.White.getAbbr(). Просто печать Tile.White вызовет toString() в перечислении, который будет печатать имя. Я думаю, вы могли бы переопределить toString(), если хотите:

public String toString(){
    return getAbbr();
}