簡體   English   中英

如何從接口的DisplayAttribute檢索數據?

[英]How can I retrieve data from DisplayAttribute of interface?

我有以下代碼:

public interface TestInterface
{
    [Display(Name = "Test Property")]
    int Property { get; }
}

class TestClass : TestAttribute
{
    public int Property { get; set; }
}

注意,interface的屬性標記有DisplayAttribute 當我嘗試從屬性獲取值時,以下代碼示例不起作用。

第一個示例:直接訪問類的屬性。

var t = new TestClass();

var a = t.GetType().GetProperty("Property").GetCustomAttributes(true);

第二個示例:將對象強制轉換為接口並訪問屬性。

var t = (TestInterface)new TestClass();

var a = t.GetType().GetProperty("Property").GetCustomAttributes(true);

但是,當我將對象作為mvc視圖的模型傳遞並調用@Html.DisplayNameFor(x => x.Property)它將返回正確的字符串"Test Property"

視圖

@model WebApplication1.Models.TestInterface
...
@Html.DisplayNameFor(x => x.Property)

呈現為

Test Property

如何在服務器端使用代碼實現相同的結果? 為什么我不能簡單地反射呢?

您可以顯式查詢關聯的接口類型以獲取注釋:

var interfaceAttributes = t.GetType()
    .GetInterfaces()
    .Select(x => x.GetProperty("Property"))
    .Where(x => x != null) // avoid exception with multiple interfaces
    .SelectMany(x => x.GetCustomAttributes(true))
    .ToList();

結果列表interfaceAttributes將包含DisplayAttribute

你可以試試這個

 var t = new TestClass();
 var a = t.GetType().GetInterface("TestInterface").GetProperty("Property").GetCustomAttributes(true);

我對Description屬性做了類似的事情。 您可以重構此代碼(或更好的方法,使其更通用),以便它也適用於Display屬性,而不僅適用於枚舉:

public enum LogCategories
{
    [Description("Audit Description")]
    Audit,
}


public static class DescriptionExtensions
{
    public static string GetDescription<T, TType>(this T enumerationValue, TType attribute)
        where T : struct
        where TType : DescriptionAttribute
    {
        Type type = enumerationValue.GetType();
        if (!type.IsEnum)
        {
            throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
        }

        //Tries to find a DescriptionAttribute for a potential friendly name
        //for the enum
        MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
        if (memberInfo != null && memberInfo.Length > 0)
        {
            object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attribute is DescriptionAttribute)
            {
                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }
            else
            {                   
            }                
        }
        //If we have no description attribute, just return the ToString of the enum
        return enumerationValue.ToString();
    }
}

如您所見,代碼使用某種反射來檢測成員上標記的任何屬性(在我的情況下為DescriptionAttribute,但也可以是DisplayAttribute),並將Description屬性返回給調用者。

用法:

string auditDescription = LogCategories.Audit.GetDescription(); // Output: "Audit Description"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM