一、關於 GetType、GetProperty、GetValue 方法的使用,如下範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| var people = new People() { Id = 1, Name = "Bill", Description = "none" };
var type = people.GetType();
var properties = type.GetProperties();
var property = type.GetProperty("Name");
var result = property.GetValue(people, null);
Console.WriteLine(result);
public class People { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } }
|
二、關於 GetField、GetCustomAttributes 方法的使用,如下範例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| using System.ComponentModel; using System.Reflection;
Week monday = Week.Monday;
Console.WriteLine(GetDescriptionText(monday));
string GetDescriptionText(Enum source) { FieldInfo fi = source.GetType().GetField(source.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes<DescriptionAttribute>(); if (attributes.Length > 0) return attributes[0].Description; else return source.ToString(); }
public enum Week { [Description("星期日")] SunDay = 0,
[Description("星期一")] Monday = 1,
[Description("星期二")] Tuesday = 2, }
|