열거 형 값을 인수로 사용하고 메서드에서 특정 속성을 가져 오는 열거 형 확장 메서드를 만드는 온라인 예제가 많이 있습니다.
namespace MVVMProj.ProjUtilities
{
public class EnumerationHelpers
{
public static string GetStatusText(this Enum value)
{
var type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null) { return null; }
var field = type.GetField(name);
if (field == null) { return null; }
var attr = Attribute.GetCustomAttribute(field, typeof(StatusTextAttribute)) as StatusTextAttribute;
if (attr == null) { return null; }
return attr.StatusText;
}
}
}
내가 궁금한 것은 메소드에 속성 유형을 전달하는 방법이 있으므로 각기 다른 속성에 대해 특정 메소드를 계속 작성할 필요가 없다는 것입니다.
이것은 미완성이지만, 내가 달성하려는 것에 대한 아이디어를 제공해야합니다.
namespace MVVMProj.ProjUtilities
{
public class EnumerationHelpers
{
public static string GetCustomAttribute(this Enum value, Type customAttr)
//Or instead of passing a Type, a string of the attribute's name
{
var type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null) { return null; }
var field = type.GetField(name);
if (field == null) { return null; }
var attr = Attribute.GetCustomAttribute(field, ....) as ....;
if (attr == null) { return null; }
return attr....;
}
}
}
모든 데이터 유형이 될 수 있으므로 문자열을 반환 할 수 없다고 가정합니다.
일반적인 방법일까요?
어떤 조언이라도 대단히 감사하겠습니다!
편집 : 사용법 :
콤보 상자에 값을 표시 할 수 있도록 사전을 만드는 열거 형을 반복합니다. 속성이 if 문의 조건과 일치하는 경우에만 항목을 추가합니다.
한 가지 더 주목할 점은 사용자 지정 속성도 열거 형이라는 것입니다.
Aybe : '항목'은 반복시 객체 일 뿐이므로 캐스트를합니다. if 문에서 오류가 발생하지만 CaseTypeAttribute를 실제 CaseType 열거 형 값과 비교하려고합니다. 해결하려면 어떻게해야합니까?
오류 :
심각도 코드 설명 프로젝트 파일 줄 억제 상태 오류 CS0019 연산자 '=='은 'SBC.CaseTypeAttribute'및 'SBC.CaseType'유형의 피연산자에 적용 할 수 없습니다.
private Dictionary<int, string> _substancetypes;
public Dictionary<int, string> SubstanceTypes
{
get
{
if (_substancetypes == null)
{
_substancetypes = new Dictionary<int, string>();
foreach (var item in Enum.GetValues(typeof(SBC.SubstanceTypeCode)))
{
var descriptionAttribute = ((SBC.SubstanceTypeCode)item).GetAttribute<SBC.CaseTypeAttribute>();
if (descriptionAttribute != null &&
descriptionAttribute == SBC.CaseType.Exposures) //Error here
{
_substancetypes.Add((int)item, CTS_MVVM.CTS_Utilities.EnumerationHelpers.GetDescriptionFromEnumValue((SBC.SubstanceTypeCode)item));
}
}
}
return _substancetypes;
}
}
이 같은?
using System;
using System.ComponentModel;
using System.Reflection;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
var descriptionAttribute = MyEnum.A.GetAttribute<DescriptionAttribute>();
}
}
public static class EnumExtensions
{
public static T GetAttribute<T>(this Enum @enum) where T : Attribute
{
var type = @enum.GetType();
var name = Enum.GetName(type, @enum);
var field = type.GetField(name);
var attribute = field.GetCustomAttribute<T>();
return attribute;
}
}
public enum MyEnum
{
[Description("A")] A,
[Description("B")] B
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다