开发者

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 e.g.

public enum EnumA
{
 A,
 B
} 

public EnumA EnumAProperty
{
 get{ return enumA;}
}

p开发者_StackOverflow社区ublic enum EnumB
{
 A,
 B
} 

public EnumB EnumBProperty
{
 get{ return enumB;}
}

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


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");
    }
}


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());


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());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜