Enum에 Description 확장메소드 추가하기
NUnit 테스트 쪽
using NUnit.Framework;
[TestFixture]
class EnumExtsTests
{
[Test]
public void TestGetDescription_Description문자열가져오기()
{
Assert.AreEqual("The operation completed successfully.",
Windows.ErrorCodes.ERROR_SUCCESS.GetDescription());
}
[Test]
public void TestGetDescription_Description속성은빈문자열획득()
{
Assert.AreEqual("",
Windows.ErrorCodes.ERROR_INVALID_FUNCTION.GetDescription());
}
}
public class Windows
{
/// <summary>
/// http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
/// </summary>
public enum ErrorCodes
{
[System.ComponentModel.Description("The operation completed successfully.")]
ERROR_SUCCESS = 0x0,
ERROR_INVALID_FUNCTION = 0x1,
[System.ComponentModel.Description("The system cannot find the file specified.")]
ERROR_FILE_NOT_FOUND = 0x1,
// ...
};
}
Description 속성관련해서 에러가 나서 왜 그런가 찾아봤는데 NUnit에서 사용하고 있어서 이름 충돌이 난 것이다.
그래서 System.ComponentModel.Description와 같이 풀네임을 지정했다.
stackoverflow에서 수정전 코드를 찾았는데 출처를 잊어버렸다. 중첩된 if문으로 되어 있어서 예외처리로 빼버렸다.
구현 쪽
using System;
using System.ComponentModel;
using System.Reflection;
public static class EnumExts
{
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
try
{
FieldInfo field = type.GetField(name);
var attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
as DescriptionAttribute;
return attr.Description;
}
catch (NullReferenceException)
{
return String.Empty;
}
}
}
NUnit으로 테스트를 해보면서 시간이 자동적으로 측정이 되는데, 리플렉션을 이용해서인지 성능이 썩 좋지 않았다.