enum
에 대해 DisplayAttribute
속성이 작동하려고하므로 사용 가능한 값 (RESTful API에 노출 됨)을 나열 할 수 있습니다..NET 코어를 사용한 열거
/// <summary>
/// A generic extension method that aids in reflecting
/// and retrieving any attribute that is applied to an `Enum`.
/// </summary>
public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute
{
var type = enumValue.GetType();
var typeInfo = type.GetTypeInfo();
var attributes = typeInfo.GetCustomAttributes<TAttribute>();
var attribute = attributes.FirstOrDefault();
return attribute;
}
/// <summary>
/// Returns a list of possible values and their associated descriptions for a type of enumeration.
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <returns></returns>
public static IDictionary<string, string> GetEnumPossibilities<TEnum>() where TEnum : struct
{
var type = typeof(TEnum);
var info = type.GetTypeInfo();
if (!info.IsEnum) throw new InvalidOperationException("Specified type is not an enumeration.");
var results = new Dictionary<string, string>();
foreach (var enumName in Enum.GetNames(type)
.Where(x => !x.Equals("Undefined", StringComparison.CurrentCultureIgnoreCase))
.OrderBy(x => x, StringComparer.CurrentCultureIgnoreCase))
{
var value = (Enum)Enum.Parse(type, enumName);
var displayAttribute = value.GetAttribute<DisplayAttribute>();
results[enumName] = $"{displayAttribute?.Name ?? enumName}: {displayAttribute?.Description ?? enumName}";
}
return results;
}
이의 사용법은 다음과 같습니다 :
var types = Reflection.GetEnumPossibilities<ProposalTypes>();
은 무엇 보인다
/// <summary>
/// Available Proposal Types
/// </summary>
public enum ProposalTypes
{
Undefined = 0,
/// <summary>
/// Propose an administrative action.
/// </summary>
[Display(Name = "Administrative", Description = "Propose an administrative action.")]
Administrative,
/// <summary>
/// Propose some other action.
/// </summary>
[Display(Name = "Miscellaneous", Description = "Propose some other action.")]
Miscellaneous
}
그때 헬퍼 방법과 같이 만들어 다음과 같이
내가 열거를 가지고 무슨 일이 일어나고 있는지, GetAttribute<TAttribute>
메쏘드에 있는데, 나는 속성을 얻으 려 할 때 w를 찾고있다. iith :
var attributes = typeInfo.GetCustomAttributes<TAttribute>();
... 결과 값은 빈 열거 형이며 따라서 null 값을 반환합니다. 내가 읽은 모든 것에서, 그것은 잘 작동 할 것이고, 나는 연관 DisplayAttribute
을 돌려 주어야한다. 그러나 나는 널 값을 얻는다.
내가 뭘 잘못하고 있니?
호기심에서 벗어나서,이 사전 (GetEnumPossibilities의 반환 값)에서 마지막으로 무엇을하고 있습니까? 이 어딘가에서 JSON으로 반환하는 경우 불필요하게 많은 문제를 겪게됩니다. JSON.NET은 속성을 올바르게 직렬화합니다. –
@HristoYankov API 소비자 프론트 엔드에 알릴 수있는 가능한 유형을 정의하는 엔드 포인트를 작성하는 데이 방법을 사용하고 있습니다. –