开发者

Business enum to DatContract Enum conversion in WCF

I have an enum

namespace Business
{
    public enum Color
   {
       Red,Green,Blue
    }
}


namespace DataContract
{
   [DataContract] 
   public enum Color
   {
       [EnumMember]
       Red,
       [EnumMember]
       Green,
       [EnumMember]
       Blue
    }
}

I have the same enum as a datacontract in WCF with same values. I need to convert the Business enum to the DataContract 开发者_如何学运维enum using a translator.

Hoe can I achieve this?


If you know both types at the time you need to do the conversion you can do something like:

Business.Color bc = Business.Color.Red;
DataContract.Color dcc = (DataContract.Color)Enum.Parse(typeof(DataContract.Color), bc.ToString())


Below, a more elegant style as the framework code.

public static class Enum<T> where T : struct
{
    public static T Parse(string value)
    {
        return (T)Enum.Parse(typeof(T), value);
    }

    public static T Convert<U>(U value) where U : struct 
    {
        if (!value.GetType().IsInstanceOfType(typeof(Enum)))
           throw new ArgsValidationException("value");

        var name = Enum.GetName(typeof (U), value);
        return Parse(name);
    }
}

//enum declaration
...    
public void Main()
{
   //Usage example
   var p = Enum<DataContract.Priority>.Convert(myEntity.Priority);
}

And voilà!


You could use something like below:

public static class ColorTranslator
{
    public static Business.Color TranslateColor(DataContract.Color from)
    {
        Business.Color to = new Business.Color();
        to.Red = from.Red;
        to.Green = from.Green;
        to.Blue = from.Blue;

        return to;
    }

    public static DataContract.Color TranslateColor(Business.Color from)
    {
        DataContract.Color to = new DataContract.Color();
        to.Red = from.Red;
        to.Green = from.Green;
        to.Blue = from.Blue;

        return to;
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜