0

我有一个枚举

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


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

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

我能做到这一点吗?

4

3 回答 3

2

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

Business.Color bc = Business.Color.Red;
DataContract.Color dcc = (DataContract.Color)Enum.Parse(typeof(DataContract.Color), bc.ToString())
于 2010-03-18T14:31:57.233 回答
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);
}

瞧!

于 2011-09-20T10:01:18.933 回答
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;
    }
}
于 2010-12-08T14:53:04.540 回答