Udostępnij przez


Jak: Pobieranie właściwości obiektów systemu drukowania bez refleksji

Użycie refleksji w celu wylistowania właściwości (i typów tych właściwości) obiektu może spowolnić działanie aplikacji. Przestrzeń nazw System.Printing.IndexedProperties umożliwia uzyskanie tych informacji bez odbicia.

Przykład

Kroki wykonania tej czynności są następujące.

  1. Utwórz wystąpienie typu. W poniższym przykładzie typ jest typem PrintQueue dostarczanym z programem Microsoft .NET Framework, ale prawie identyczny kod powinien działać w przypadku typów pochodzących z PrintSystemObject.

  2. Utwórz PrintPropertyDictionary na podstawie PropertiesCollectiontypu . Właściwość Value każdego wpisu w tym słowniku jest obiektem jednego z typów pochodzących z PrintProperty.

  3. Wylicz członków słownika. Dla każdego z nich wykonaj następujące czynności.

  4. Rzutuj w górę wartość każdego wpisu do PrintProperty i użyj jej do utworzenia obiektu PrintProperty.

  5. Pobierz typ Value każdego obiektu 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()

Zobacz także