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

使用反射列举对象的属性(以及这些属性的类型)会降低应用程序性能。 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
            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()


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

请参见

参考

PrintProperty

PrintSystemObject

System.Printing.IndexedProperties

PrintPropertyDictionary

LocalPrintServer

PrintQueue

DictionaryEntry

概念

WPF 中的文档

打印概述