C# 反射(Reflection)
反射指程序可以訪問、檢測和修改它本身狀態(tài)或行為的一種能力。
程序集包含模塊,而模塊包含類型,類型又包含成員。反射則提供了封裝程序集、模塊和類型的對象。
您可以使用反射動態(tài)地創(chuàng)建類型的實(shí)例,將類型綁定到現(xiàn)有對象,或從現(xiàn)有對象中獲取類型。然后,可以調(diào)用類型的方法或訪問其字段和屬性。
優(yōu)缺點(diǎn)
優(yōu)點(diǎn):
1、反射提高了程序的靈活性和擴(kuò)展性。
2、降低耦合性,提高自適應(yīng)能力。
3、它允許程序創(chuàng)建和控制任何類的對象,無需提前硬編碼目標(biāo)類。
缺點(diǎn):
1、性能問題:使用反射基本上是一種解釋操作,用于字段和方法接入時要遠(yuǎn)慢于直接代碼。因此反射機(jī)制主要應(yīng)用在對靈活性和拓展性要求很高的系統(tǒng)框架上,普通程序不建議使用。
2、使用反射會模糊程序內(nèi)部邏輯;程序員希望在源代碼中看到程序的邏輯,反射卻繞過了源代碼的技術(shù),因而會帶來維護(hù)的問題,反射代碼比相應(yīng)的直接代碼更復(fù)雜。
項(xiàng)目中用到 做個筆記。
public static Type GetType(string TypeName)
{
// Try Type.GetType() first. This will work with types defined
// by the Mono runtime, in the same assembly as the caller, etc.
var type = Type.GetType(TypeName);
// If it worked, then we're done here
if (type != null)
return type;
// If the TypeName is a full name, then we can try loading the defining assembly directly
if (TypeName.Contains("."))
{
// Get the name of the assembly (Assumption is that we are using
// fully-qualified type names)
var assemblyName = TypeName.Substring(0, TypeName.IndexOf('.'));
// Attempt to load the indicated Assembly
var assembly = Assembly.Load(assemblyName);
if (assembly == null)
return null;
// Ask that assembly to return the proper Type
type = assembly.GetType(TypeName);
if (type != null)
return type;
}
// If we still haven't found the proper type, we can enumerate all of the
// loaded assemblies and see if any of them define the type
//獲取包含調(diào)用當(dāng)前所執(zhí)行代碼的方法的程序集
var currentAssembly = Assembly.GetExecutingAssembly();
var referencedAssemblies = currentAssembly.GetReferencedAssemblies();
foreach (var assemblyName in referencedAssemblies)
{
// Load the referenced assembly
var assembly = Assembly.Load(assemblyName);
if (assembly != null)
{
// See if that assembly defines the named type
type = assembly.GetType(TypeName);
if (type != null)
return type;
}
}
// The type just couldn't be found...
return null;
}