简体   繁体   中英

How to obtain one value by index (int) in enum, in unidimentional enum in C#

I can't find this question related to unidimentional enums and i think is different with bi-dimentional ones, so let's start.

Let's say i have this enum:

public enum TileType {Empty, Floor};

and i have this elements inside my class:

private TileType _type = TileType.Empty;

public TileType Type {
        get {
            return _type;
        }
        set {
            TileType oldType = _type;
                _type = value;
            }
    }

How can i get "Empty" or "Floor" using an index (int) to retreive them in C#?

And, like a side-question without any tipe of priority...

how would you retreive the information stored in 'oldType' TileType? (this sub questions, if you want it to answer it, answer it in the comments plz)

PS: Let's asume for purpose of this question than we already think than the enum is the way to go in this code, and than i already check the usefullness of other types of list.

Any improvement to this question or request for clarification would be much apreciated too

Thanks in advance

Enumerations are not indexed, but they do have underlying values... in your case Empty and Floor are 0 and 1, respectively.

To reference TileType.Floor , you could use this:

var floor = (TileType)1;

Since you asked about something like Dictionary.GetKey() , there are methods available on the Enum class, but nothing exactly like that.

You could write your own extension method. Give this a try, for example:

public static class EnumExt
{
    public static T GetKey<T>(int value) where T : struct
    {
        T result;

        if (!Enum.TryParse(value.ToString(), out result))
            // no match found - throw an exception?

        return result;
    }
}

Which you could then call:

var floor = EnumExt.GetKey<TileType>(1);

Try this one, similar question I believe? Retrieve value of Enum based on index - c#

You should put your oldType as a variable outside the Type property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM