简体   繁体   中英

C# Copying Enumeration from one object to another

I have two very similar but not identical C# objects. I am copying the values from one class to another.

Each class has some properties that expose an enumeration type. The inside of the enumerations are the same but the names are different eg

public enum EnumA
{
 A,
 B
} 

public EnumA EnumAProperty
{
 get{ return enumA;}
}

public enum EnumB
{
 A,
 B
} 

public EnumB EnumBProperty
{
 get{ return enumB;}
}

I want to assign the value returned from EnumBProperty to EnumAProperty is this possible?

Each enum member has a corresponding integer value.
By default, these values are assigned in ascending order, starting with 0 .

If the order of the items in the enums (and thus their numeric values) are the same, you can just cast the numeric value to EnumB to get the EnumB member with the same value:

 EnumBProperty = (EnumB)(int)EnumAProperty;

If not, you need to re-parse it:

EnumBProperty = (EnumB)Enum.Parse(typeof(EnumB), EnumAProperty.ToString());

You can do via casting but I would not recommend it as it is fragile — if any of the enum members are reordered or new items added the result may not be what you expect.

EnumAProperty = (EnumA) EnumBProperty;

Even worse with the casting is if you have items in your source enum with no equivalent in the destination — below there are more colours than shapes:

enum Color { Red = 0, Yellow = 1, Blue = 2 };
enum Shape ( Square = 0, Triangle = 1 };

Color color = Color.Red;
Shape shape = (Shape) color;

shape could end up with the value 2 even though this value is not defined.

Instead, I'd suggest you use a switch statement to map:

EnumAProperty = ConvertToA(EnumBProperty);

...

private static EnumA ConvertToA(EnumBProperty b)
{
    switch (b)
    {
        case EnumB.Flannel: return EnumA.HandTowel;
        case EnemB.Vest: return EnumA.UnderShirt;
        ...
        default: throw new ArgumentOutOfRangeException("b");
    }
}

As long as both enum's of different types you can'not assign it directly. You can define integer offset for an items so you can assign values through the integer value

public enum EnumA 
{  
 A = 0,  
 B = 1
}   

public enum EnumB
{  
 A = 0,  
 B = 1
}   

EnumBPropertry = (int)EnumAProperty

You could either cast it to an integer or convert it to a string and then do an Enum.Parse on it.

Try the following:

EnumAProperty = (EnumA)Enum.Parse(typeof(EnumA), EnumBProperty.ToString);
EnumBProperty = (EnumB)Enum.Parse(typeof(EnumB), EnumAProperty.ToString());

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