سؤال

لدي تعداد

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


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

لدي نفس التعداد كقواعد DataContract في WCF مع نفس القيم. أحتاج إلى تحويل تعداد الأعمال إلى تعداد DataContract باستخدام مترجم.

مجرفة هل يمكنني تحقيق ذلك؟

هل كانت مفيدة؟

المحلول

إذا كنت تعرف كلا النوعين في الوقت الذي تحتاج فيه إلى إجراء التحويل ، يمكنك القيام بشيء مثل:

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

نصائح أخرى

أدناه ، نمط أكثر أناقة مثل رمز الإطار.

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

وفويلا!

يمكنك استخدام شيء مثل أدناه:

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;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top