如何:获取不带反射的打印系统对象属性

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

示例:

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

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

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

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

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

  5. 获取每个 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()

另请参阅