如何:取得列印系統物件屬性但不使用反映
在物件上使用反映來將屬性(以及這些屬性的類型)逐一化,可能會降低應用程式效能。 命名空間 System.Printing.IndexedProperties 提供一種方法來取得這項資訊,而不需使用反映。
範例
執行此動作的步驟如下。
建立 型別的執行個體。 在下列範例中,類型是 PrintQueue 隨附于 Microsoft .NET Framework 的類型,但幾乎完全相同的程式碼應該適用于衍生自 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()