Để bắt đầu, chúng ta có 1 class như sau:

using System;
using System.Collections.Generic;

namespace CuaHangSach.Models
{
    public partial class Book
    {
      	[Display(Name = "ID sách")]
        public long ID { get; set; }
      
      	[Display(Name = "Tên sách")]
        public string name { get; set; }
    }
}

Chúng ta cần lấy tên thuộc tính hiển thị, ví dụ như thuộc tính name của class Book có tên hiển thị là “Tên sách” .

Đây là cách thực hiện:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace CuaHangSach.Models
{
    public class DisplayName
    {
        public static Dictionary<string, string> GetDisplayName<T>(List<string> Include)
        {
            PropertyInfo[] props = typeof(T).GetProperties();
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (PropertyInfo prop in props)
            {
                if (Include.Contains(prop.Name) == false)
                    continue;
                MemberInfo property = typeof(T).GetProperty(prop.Name);
                string displayName = property.GetCustomAttribute<DisplayAttribute>()?.Name;
                dict.Add(prop.Name, displayName);
            }
            return dict;
        }
    }
}

Cách dùng:

Dictionary<string, string> dict = DisplayName.GetDisplayName<Book>(new List<string>{"ID", "name"});
string dispName = dict["name"];

Tagged in: