一般情况下我们的返回实体都为英文命名,某些时候我们想自定义返回的属性名称。在C#中,不能直接通过内置的反射API来获取属性的“自定义名字”,因为属性本身在元数据中并没有这样的概念。但是,可以使用自定义属性(Attribute)来为类成员(如属性)添加额外的元数据,并通过反射来读取这些元数据。
首先,定义自定义的DisplayNameAttribute:
using System; [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class DisplayNameAttribute : Attribute
{ public string DisplayName { get; } public DisplayNameAttribute(string displayName) { DisplayName = displayName; }
}
然后,在Test类中使用这个自定义属性:
public class Test
{ [DisplayName("姓名")] public string? Name { get; set; } [DisplayName("年龄")] public int? Age { get; set; }
}
然后可以通过反射来获取这些自定义的显示名称:
using System;
using System.Reflection; public class ReflectionExample
{ public static void Main() { Type testType = typeof(Test); foreach (PropertyInfo property in testType.GetProperties()) { DisplayNameAttribute displayNameAttribute = property.GetCustomAttribute<DisplayNameAttribute>(); if (displayNameAttribute != null) { Console.WriteLine($"属性名: {property.Name}, 自定义显示名: {displayNameAttribute.DisplayName}"); } else { Console.WriteLine($"属性名: {property.Name}, 没有自定义显示名"); } } }
}
当你运行上面的Main方法时,它将输出:
属性名: Name, 自定义显示名: 姓名
属性名: Age, 自定义显示名: 年龄