在屬性與程式專案相關聯之後,反射可用來查詢其存在和值。 .NET 提供 MetadataLoadContext,您可以使用它來檢查無法載入執行的程式代碼。
MetadataLoadContext
無法執行載入內容中的 MetadataLoadContext 程式代碼。 這表示無法建立自定義屬性的實例,因為這需要執行其建構函式。 若要載入及檢查內容中的 MetadataLoadContext 自訂屬性,請使用 類別 CustomAttributeData 。 您可以使用靜態 CustomAttributeData.GetCustomAttributes 方法的適當多載來取得這個類別的實例。 如需詳細資訊,請參閱 如何:使用MetadataLoadContext檢查元件內容。
執行環境
在執行內容中,查詢屬性的主要反映方法是 MemberInfo.GetCustomAttributes 和 Attribute.GetCustomAttributes。
自訂屬性的可存取性會針對至其附加的組件進行檢查。 這相當於檢查附加自定義屬性之元件中型別的方法是否可以呼叫自定義屬性的建構函式。
檢查類型參數的可見性和可存取性的Assembly.GetCustomAttributes(Boolean) 方法。 只有包含使用者定義型別的元件中的程式代碼,才能使用 GetCustomAttributes擷取該類型的自定義屬性。
下列 C# 範例是典型的自訂屬性設計模式。 其說明運行時間自定義屬性反映模型。
System.DLL
public class DescriptionAttribute : Attribute
{
}
System.Web.DLL
internal class MyDescriptionAttribute : DescriptionAttribute
{
}
public class LocalizationExtenderProvider
{
[MyDescriptionAttribute(...)]
public CultureInfo GetLanguage(...)
{
}
}
如果運行時間嘗試擷取附加至 DescriptionAttribute 方法之公用自定義屬性類型的GetLanguage自定義屬性,它會執行下列動作:
- 運行時間檢查類型參數
DescriptionAttribute對於Type.GetCustomAttributes(Type type)是否為公共的,從而是可見且可訪問的。 - 執行時間會檢查衍生自
MyDescriptionAttribute的使用者定義型別DescriptionAttribute是否在 System.Web.dll 元件中可見且可存取,並確認它已附加至方法GetLanguage()。 - 執行階段會檢查
MyDescriptionAttribute的建構函式是否在 System.Web.dll 程式集中可見且可存取。 - 執行階段會使用自訂屬性參數呼叫
MyDescriptionAttribute的建構函式,並將新的物件傳回給呼叫端。
自定義屬性反映模型可能會在定義型別的元件之外洩漏用戶定義型別的實例。 這與運行時系統庫中傳回使用者定義類型實例的成員沒有不同,例如 Type.GetMethods 傳回 RuntimeMethodInfo 物件陣列。 若要防止用戶端探索使用者定義自定義屬性類型的相關信息,請定義類型的成員為非公用。
下列範例示範使用反映來存取自定義屬性的基本方式。
using System;
public class ExampleAttribute : Attribute
{
private string stringVal;
public ExampleAttribute()
{
stringVal = "This is the default string.";
}
public string StringValue
{
get { return stringVal; }
set { stringVal = value; }
}
}
[Example(StringValue="This is a string.")]
class Class1
{
public static void Main()
{
System.Reflection.MemberInfo info = typeof(Class1);
foreach (object attrib in info.GetCustomAttributes(true))
{
Console.WriteLine(attrib);
}
}
}
Public Class ExampleAttribute
Inherits Attribute
Private stringVal As String
Public Sub New()
stringVal = "This is the default string."
End Sub
Public Property StringValue() As String
Get
Return stringVal
End Get
Set(Value As String)
stringVal = Value
End Set
End Property
End Class
<Example(StringValue:="This is a string.")> _
Class Class1
Public Shared Sub Main()
Dim info As System.Reflection.MemberInfo = GetType(Class1)
For Each attrib As Object In info.GetCustomAttributes(true)
Console.WriteLine(attrib)
Next attrib
End Sub
End Class