열거 확장 방법
vs2008에서는 모든 열거에 적용되는 확장 메서드를 작성할 수 있습니까?
특정 열거에 대해 확장 메서드를 작성할 수 있다는 것을 알고 있지만 단일 확장 메서드를 사용하여 모든 열거를 수행 할 수 있기를 원합니다. 이것이 가능한가?
예, 기본 Enum
유형 에 대한 코드입니다.
public static void Something(this Enum e)
{
// code here
}
Enum.GetUnderlyingType
단점은 enum의 기본 유형이 무엇인지에 따라을 사용하여 실제 기본 유형을 찾고 , 캐스팅하고, 다른 분기를 내려가는 것과 같은 매우 불쾌한 일을 끝내게 될 것 입니다.하지만 좋은 용도를 찾을 수 있습니다. (예 : 모든 열거 형에 적용되는 IsOneOf
및 IsCombinationOf
메서드가 있습니다).
추신 : 병 조언하지만, 당신이 사용할 수있는 방법을 작성할 때 기억 float
하고 double
당신이 어떤 사람들을 위해 특별한 경우뿐만 아니라 부호 값을해야하므로 열거 형에 대한 기본 유형을 등을.
그래 넌 할수있어. 대상 확장 유형은 유형 Enum
입니다. C #에서는 다음과 같이 수행됩니다.
public static void EnumExtension(this Enum e)
{
}
또는 VB에서 이와 같이 :
<Extension()> _
Public Sub EnumExtension(ByVal s As Enum)
End Sub
참고로 여기에 내가 사용할 수 있었던 Enum Extension 메서드의 좋은 예가 있습니다. 열거 형에 대해 대소 문자를 구분하지 않는 TryParse () 함수를 구현합니다.
public static class ExtensionMethods
{
public static bool TryParse<T>(this Enum theEnum, string strType,
out T result)
{
string strTypeFixed = strType.Replace(' ', '_');
if (Enum.IsDefined(typeof(T), strTypeFixed))
{
result = (T)Enum.Parse(typeof(T), strTypeFixed, true);
return true;
}
else
{
foreach (string value in Enum.GetNames(typeof(T)))
{
if (value.Equals(strTypeFixed,
StringComparison.OrdinalIgnoreCase))
{
result = (T)Enum.Parse(typeof(T), value);
return true;
}
}
result = default(T);
return false;
}
}
}
다음과 같은 방식으로 사용합니다.
public enum TestEnum
{
A,
B,
C
}
public void TestMethod(string StringOfEnum)
{
TestEnum myEnum;
myEnum.TryParse(StringOfEnum, out myEnum);
}
이 코드를 만드는 데 도움을주기 위해 방문한 두 사이트는 다음과 같습니다.
Enum에 대한 대소 문자를 구분하지 않는 TryParse
여기 또 다른 예가 있습니다. 또한 임시 변수를 만들고 초기화하는 것보다 더 좋은 IMHO입니다.
public static class ExtensionMethods
{
public static void ForEach(this Enum enumType, Action<Enum> action)
{
foreach (var type in Enum.GetValues(enumType.GetType()))
{
action((Enum)type);
}
}
}
public enum TestEnum { A,B,C }
public void TestMethod()
{
default(TestEnum).ForEach(Console.WriteLine);
}
다음과 같이 변환 방법을 구현할 수도 있습니다.
public static class Extensions
{
public static ConvertType Convert<ConvertType>(this Enum e)
{
object o = null;
Type type = typeof(ConvertType);
if (type == typeof(int))
{
o = Convert.ToInt32(e);
}
else if (type == typeof(long))
{
o = Convert.ToInt64(e);
}
else if (type == typeof(short))
{
o = Convert.ToInt16(e);
}
else
{
o = Convert.ToString(e);
}
return (ConvertType)o;
}
}
다음은 사용 예입니다.
int a = MyEnum.A.Convert<int>();
Sometimes there is a need to convert from one enum to another, based on the name or value of the enum. Here is how it can be done nicely with extension methods:
enum Enum1 { One = 1, Two = 2, Three = 3 };
enum Enum2 { Due = 2, Uno = 1 };
enum Enum3 { Two, One };
Enum2 e2 = Enum1.One.ConvertByValue<Enum2>();
Enum3 e3 = Enum1.One.ConvertByName<Enum3>();
Enum3 x2 = Enum1.Three.ConvertByValue<Enum3>();
public static class EnumConversionExtensions
{
public static T ConvertByName<T>(this Enum value)
{
return (T)Enum.Parse(typeof(T), Enum.GetName(value.GetType(), value));
}
public static T ConvertByValue<T>(this Enum value)
{
return (T)((dynamic)((int)((object)value)));
}
}
Another example of making Enum extension - but this time it returns the input enum type.
public static IEnumerable<T> toElementsCollection<T>(this T value) where T : struct, IConvertible
{
if (typeof(T).IsEnum == false) throw new Exception("typeof(T).IsEnum == false");
return Enum.GetValues(typeof(T)).Cast<T>();
}
Example of usage:
public enum TestEnum { A,B,C };
TestEnum.A.toElementsCollection();
ReferenceURL : https://stackoverflow.com/questions/276585/enumeration-extension-methods
'UFO ET IT' 카테고리의 다른 글
hadoop은 로컬 파일 시스템 폴더를 HDFS로 복사합니다. (0) | 2021.01.10 |
---|---|
AVPlayer 비디오 재생이 종료되는시기를 감지하는 방법 (0) | 2021.01.10 |
IdentityHashMap의 사용 사례 (0) | 2021.01.10 |
프로그래밍 방식으로 C ++ 클래스 이름 검색 (0) | 2021.01.10 |
DataView에서 행 반복 (0) | 2021.01.10 |