如何:在不使用反射的情况下获得打印系统对象属性

使用反射逐项列出对象上的属性(以及这些属性的类型)可能会降低应用程序性能。 System.Printing.IndexedProperties 命名空间提供了一种在不使用反射的情况下获得此信息的方法。

示例

执行此操作的步骤如下所示。

  1. 创建 类型的实例。 在下面的示例中,类型是 Microsoft .NET Framework 附带的 PrintQueue 类型,但几乎相同的代码应该适用于从 PrintSystemObject 派生的类型。

  2. 从类型的 PropertiesCollection 创建 PrintPropertyDictionary。 此字典中每个条目的 Value 属性是从 PrintProperty 派生的类型之一的对象。

  3. 枚举字典的成员。 对于每个成员,请执行以下操作。

  4. 将每个条目的值向上转换为 PrintProperty,并使用它来创建 PrintProperty 对象。

  5. 获取每个 PrintProperty 对象的 Value 类型。


// 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()

另请参阅