40
1
using System;
2
using System.ComponentModel.DataAnnotations;
3
using System.Linq;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
var obj = new Student()
10
{
11
Name = "王大明",
12
Birthday = DateTime.Now
13
};
14
15
Console.WriteLine(obj.GetAttributeFrom<DisplayAttribute>(nameof(Student.Name)).Name);
16
Console.WriteLine(obj.Name);
17
Console.WriteLine(obj.GetAttributeFrom<DisplayAttribute>(nameof(Student.Birthday)).Name);
18
Console.WriteLine(obj.Birthday);
19
}
20
21
public class Student
22
{
23
[Display(Name = "姓名")]
24
public string Name { get; set; }
25
26
[Display(Name = "生日")]
27
public DateTime Birthday { get; set; }
28
}
29
}
30
31
public static class ObjectExtension
32
{
33
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
34
{
35
var attributeType = typeof(T);
36
var property = instance.GetType().GetProperty(propertyName);
37
if (property == null) return default(T);
38
return (T) property.GetCustomAttributes(attributeType, false).FirstOrDefault();
39
}
40
}
Cached Result