开发者

How do I point a variable at an Enum?

开发者 https://www.devze.com 2023-03-27 20:06 出处:网络
For example I\'d like to substitute Dogs for Cats in the code below (the string \"fluffy\" in this instance will always be retrieved from elsewhere and set from the same Enum that will be \'t\' in thi

For example I'd like to substitute Dogs for Cats in the code below (the string "fluffy" in this instance will always be retrieved from elsewhere and set from the same Enum that will be 't' in this example).

The code btw doesn't work but you can see what I am trying to do.

private enum Cats { Fluffy, Furry, Bald };
private enum Dogs { Big, Fat, Ugly };

sometype CurrentEnum = Cats;

var x = Enum.Parse(typeof(CurrentEnum), "fluffy", true); 

UPDATE 1

From the responses I don't think I've made it clear what I am trying to achieve so I've made some changes.

Sometimes CurrentEnum will be pointing to Cats, sometimes to Dogs (the string "fluffy" will be different accordingly). Hence in this example I can return "fluffy" as an Enum and then get the next item in the sequence, "Furry" if need be. And if CurrentEnum points to Dogs and the string is "Fat" I can get to Dogs.Ugly. Make sense?

UPDATE 2

Here's where I'm at:

class Program
{
    enum Cats { Fluffy, Furry, Bald };
    enum Dogs { Big, Fat, Ugly };

    static Type CurrentEnum;

    static void Main(string[] args)
    {
        CurrentEnum = typeof(Cats); // set elsewhere in program

        Int32 i = (Int32)Enum.Parse(CurrentEnum, "fluffy", true);
        Array a = CurrentEnum.GetEnumValues();

        Console.WriteLine(a.GetValue(i + 开发者_开发技巧1)); // next in sequence
    }
}

Notice that CurrentEnum can be set elsewhere in the program, but retrieved in order to determine the next value in the enumeration when needed. I find it a bit strange that I have to dump my enumeration to an array before I can access the values.

UPDATE 3

I've now satisfied myself that this is the best solution:

class Program
{
    enum Cats { Fluffy, Furry, Bald };
    enum Dogs { Big, Fat, Ugly };

    static Type CurrentEnum = typeof(Cats);

    static void Main(string[] args)
    {
        Int32 i = (Int32)Enum.Parse(CurrentEnum, "Bald", true);           
        i = i == CurrentEnum.GetEnumValues().Length - 1 ? 0 : i++;
        String nextValue = CurrentEnum.GetEnumValues().GetValue(i).ToString();

        Console.WriteLine(nextValue);
        Console.ReadKey();
    }
}


I will provide you a little example using generics, give you more choice.

class Program
{
    private enum Cats { Fluffy, Furry, Bald };
    private enum Dogs { Big, Fat, Ugly };

    static void Main ( string [] args )
    {
        var testValue = "Fluffy";

        Cats? tempCat;
        Dogs? tempDog;

       if(  TryParse( testValue, false, out tempCat ) )
           Console.WriteLine ( "'{0}' was parsed to a cat", testValue );

        testValue = "Ugly";

        if ( TryParse ( testValue, false, out tempDog ) )
            Console.WriteLine ( "'{0}' was parsed to a dog", testValue );

        Console.ReadKey ( );

    }

    public static bool TryParse<T> ( string value, bool ignoreCase, out T? result ) where T : struct, IComparable, IFormattable, IConvertible
    {
        result = null;
        if ( !Enum.IsDefined ( typeof ( T ), value ) )
            return false;

        result = ( T )Enum.Parse ( typeof ( T ), value, ignoreCase );
        return true;
    }
}

You don't have to go the "TryParse" way if you want it more dynamic. You could modify it to return T and have it throw exceptions if the passed string is not defined or if T is not an enum, e.g.

public static T Parse<T> ( string value, bool ignoreCase = false) where T : struct, IComparable, IFormattable, IConvertible
    {
        if ( !typeof ( T ).IsEnum )
            throw new ArgumentException( string.Format( "The type ({0}) must be an enum", typeof ( T ).FullName ) );


        if ( !Enum.IsDefined ( typeof ( T ), value ) )
            throw new ArgumentException( string.Format( "{0} is not defined for the enum {1}", value, typeof ( T ).FullName ) );

        return ( T )Enum.Parse ( typeof ( T ), value, ignoreCase );
    }

EDIT: Sorry, and you would call the 2nd method as such, handling exceptions of course:

var x = Parse< Cats >( testValue );


The last two lines can be replaced with

Cats x = (Cats)Enum.Parse(typeof(Cats), "fluffy", true);

This is an alternative to IAbstract's perfectly good answer if you also want to avoid using var.


Try this code out:

class Program
{
    enum Cats { Fluffy, Furry, Bald };
    enum Dogs { Big, Fat, Ugly };

    static void Main(string[] args)
    {
        string name = "Fluffy";
        Type currentEnum = typeof(Cats);

        if(currentEnum.Equals(typeof(Cats)))
        {
            Cats cat = (Cats)Enum.Parse(typeof(Cats), name);
            Console.WriteLine("old " + cat);                        // Prints "old Fluffy"
            Console.WriteLine("new " + (cat + 1));                  // Prints "new Furry"  // TODO: Add error check for the + 1
        }
        else if (currentEnum.Equals(typeof(Dogs)))
        {
            Dogs dog = (Dogs)Enum.Parse(typeof(Cats), name);
            Console.WriteLine("old " + dog);
            Console.WriteLine("new " + (dog + 1));
        }

        Console.ReadKey();
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消