在物件上使用反映來條列屬性 (以及這些屬性的類型),可能會降低應用程式效能。 System.Printing.IndexedProperties 命名空間提供無須使用反映即可取得這項資訊的方法。
範例
此做法的具體步驟如下。
建立 型別的執行個體。 在下列範例中,類型是隨附於 .NET Framework Microsoft 的 PrintQueue 類型,但衍生自 PrintSystemObject 的類型應該適用幾乎相同的程式碼。
從類型的 PrintPropertyDictionary 建立 PropertiesCollection。 此字典中每個項目的 Value 屬性是衍生自 PrintProperty 之其中一種類型的物件。
列舉字典的成員。 針對各個成員,請執行下列動作。
將每個項目的值向上轉換為 PrintProperty,並用它來建立 PrintProperty 物件。
取得每個 Value 物件之 PrintProperty 的類型。
// Enumerate the properties, and their types, of a queue without using Reflection
LocalPrintServer localPrintServer = new LocalPrintServer();
PrintQueue defaultPrintQueue = LocalPrintServer.GetDefaultPrintQueue();
PrintPropertyDictionary printQueueProperties = defaultPrintQueue.PropertiesCollection;
Console.WriteLine("These are the properties, and their types, of {0}, a {1}", defaultPrintQueue.Name, defaultPrintQueue.GetType().ToString() +"\n");
foreach (DictionaryEntry entry in printQueueProperties)
{
PrintProperty property = (PrintProperty)entry.Value;
if (property.Value != null)
{
Console.WriteLine(property.Name + "\t(Type: {0})", property.Value.GetType().ToString());
}
}
Console.WriteLine("\n\nPress Return to continue...");
Console.ReadLine();
' Enumerate the properties, and their types, of a queue without using Reflection
Dim localPrintServer As New LocalPrintServer()
Dim defaultPrintQueue As PrintQueue = LocalPrintServer.GetDefaultPrintQueue()
Dim printQueueProperties As PrintPropertyDictionary = defaultPrintQueue.PropertiesCollection
Console.WriteLine("These are the properties, and their types, of {0}, a {1}", defaultPrintQueue.Name, defaultPrintQueue.GetType().ToString() + vbLf)
For Each entry As DictionaryEntry In printQueueProperties
Dim [property] As PrintProperty = CType(entry.Value, PrintProperty)
If [property].Value IsNot Nothing Then
Console.WriteLine([property].Name & vbTab & "(Type: {0})", [property].Value.GetType().ToString())
End If
Next entry
Console.WriteLine(vbLf & vbLf & "Press Return to continue...")
Console.ReadLine()