WCF中的业务枚举到DatContract枚举转换

时间:2010-03-18 14:19:16

标签: wcf translation enums datacontracts

我有一个枚举

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


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

我在WCF中具有与具有相同值的datacontract相同的枚举。 我需要使用翻译器将Business枚举转换为DataContract枚举。

我可以实现这个目标吗?

3 个答案:

答案 0 :(得分:2)

如果您在需要进行转换时知道这两种类型,则可以执行以下操作:

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

答案 1 :(得分:1)

下面,作为框架代码更优雅的风格。

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

瞧!

答案 2 :(得分:0)

您可以使用以下内容:

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