反射取值——特性、屬性(C#)
C# 反射(Reflection)
反射指程式可以通路、檢測和修改它本身狀态或行為的一種能力。
程式集包含子產品,而子產品包含類型,類型又包含成員。反射則提供了封裝程式集、子產品和類型的對象。
您可以使用反射動态地建立類型的執行個體,将類型綁定到現有對象,或從現有對象中擷取類型。然後,可以調用類型的方法或通路其字段和屬性。
優缺點
優點:
1、反射提高了程式的靈活性和擴充性。
2、降低耦合性,提高自适應能力。
3、它允許程式建立和控制任何類的對象,無需提前寫死目标類。
缺點:
1、性能問題:使用反射基本上是一種解釋操作,用于字段和方法接入時要遠慢于直接代碼。是以反射機制主要應用在對靈活性和拓展性要求很高的系統架構上,普通程式不建議使用。
2、使用反射會模糊程式内部邏輯;程式員希望在源代碼中看到程式的邏輯,反射卻繞過了源代碼的技術,因而會帶來維護的問題,反射代碼比相應的直接代碼更複雜。
反射(Reflection)的用途
反射(Reflection)有下列用途:
它允許在運作時檢視特性(attribute)資訊。
它允許審查集合中的各種類型,以及執行個體化這些類型。
它允許延遲綁定的方法和屬性(property)。
它允許在運作時建立新類型,然後使用這些類型執行一些任務。
接下來我們談談如何反射取值:
直接上代碼
[Obsolete("123")]
class Program
{
// 定義一個奧特曼類
public class AutoMan
{
public int age { get; set; }
public string name { get; set; }
public short length { get; set; }
}
static void Main(string[] args)
{
// 執行個體化并給初值
AutoMan autoMan = new AutoMan()
{
age = 18,
name = "迪迦",
length = 3
};
Type type = autoMan.GetType();
PropertyInfo[] propertyInfos = type.GetProperties();
Console.WriteLine("奧特曼的屬性值如下所示:");
foreach (PropertyInfo propertyInfo in propertyInfos)
{
object res = propertyInfo.GetValue(autoMan);
Console.Write(propertyInfo.Name + ": " + res.ToString() + " ");
}
Console.WriteLine();
Type type2 = typeof(Program);
IEnumerable<Attribute> attributes = type2.GetCustomAttributes(); // 獲得Program類的所有特性
Console.WriteLine("Program的特性如下所示:");
foreach (Attribute attribute in attributes)
{
var d = attribute as ObsoleteAttribute; // Attribute是所有特性的父類,通過拆箱代替強轉
if (d != null)
{
Console.Write(d.IsError + " ");
Console.Write(d.Message + " ");
Console.Write(d.TypeId + " ");
}
}
Console.WriteLine();
}
}
輸出結果:
