WCF의 Datcontract Enum 변환에 대한 비즈니스 열거
-
20-09-2019 - |
문제
나는 열거가있다
namespace Business
{
public enum Color
{
Red,Green,Blue
}
}
namespace DataContract
{
[DataContract]
public enum Color
{
[EnumMember]
Red,
[EnumMember]
Green,
[EnumMember]
Blue
}
}
나는 동일한 값을 가진 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);
}
그리고 Voilà!
아래와 같은 것을 사용할 수 있습니다.
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;
}
}
제휴하지 않습니다 StackOverflow