Поделиться через


PrintPropertyDictionary Класс

Определение

Представляет коллекцию свойств и значений, связанных с объектом в System.Printing пространстве имен.

public ref class PrintPropertyDictionary : System::Collections::Hashtable, IDisposable
public ref class PrintPropertyDictionary : System::Collections::Hashtable, IDisposable, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
[System.Serializable]
public class PrintPropertyDictionary : System.Collections.Hashtable, IDisposable
public class PrintPropertyDictionary : System.Collections.Hashtable, IDisposable
public class PrintPropertyDictionary : System.Collections.Hashtable, IDisposable, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[<System.Serializable>]
type PrintPropertyDictionary = class
    inherit Hashtable
    interface ISerializable
    interface IDeserializationCallback
    interface IDisposable
type PrintPropertyDictionary = class
    inherit Hashtable
    interface IDisposable
    interface IDeserializationCallback
    interface ISerializable
Public Class PrintPropertyDictionary
Inherits Hashtable
Implements IDisposable
Public Class PrintPropertyDictionary
Inherits Hashtable
Implements IDeserializationCallback, IDisposable, ISerializable
Наследование
PrintPropertyDictionary
Атрибуты
Реализации

Примеры

В следующем примере показано, как использовать этот класс для установки второго принтера, который отличается от его свойств от существующего принтера только в расположении, порту и общем состоянии.

LocalPrintServer myLocalPrintServer = new LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer);
PrintQueue sourcePrintQueue = myLocalPrintServer.DefaultPrintQueue;
PrintPropertyDictionary myPrintProperties = sourcePrintQueue.PropertiesCollection;

// Share the new printer using Remove/Add methods
PrintBooleanProperty shared = new PrintBooleanProperty("IsShared", true);
myPrintProperties.Remove("IsShared");
myPrintProperties.Add("IsShared", shared);

// Give the new printer its share name using SetProperty method
PrintStringProperty theShareName = new PrintStringProperty("ShareName", "\"Son of " + sourcePrintQueue.Name +"\"");
myPrintProperties.SetProperty("ShareName", theShareName);

// Specify the physical location of the new printer using Remove/Add methods
PrintStringProperty theLocation = new PrintStringProperty("Location", "the supply room");
myPrintProperties.Remove("Location");
myPrintProperties.Add("Location", theLocation);

// Specify the port for the new printer
String[] port = new String[] { "COM1:" };

// Install the new printer on the local print server
PrintQueue clonedPrinter = myLocalPrintServer.InstallPrintQueue("My clone of " + sourcePrintQueue.Name, "Xerox WCP 35 PS", port, "WinPrint", myPrintProperties);
myLocalPrintServer.Commit();

// Report outcome
Console.WriteLine("{0} in {1} has been installed and shared as {2}", clonedPrinter.Name, clonedPrinter.Location, clonedPrinter.ShareName);
Console.WriteLine("Press Return to continue ...");
Console.ReadLine();
Dim myLocalPrintServer As New LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer)
Dim sourcePrintQueue As PrintQueue = myLocalPrintServer.DefaultPrintQueue
Dim myPrintProperties As PrintPropertyDictionary = sourcePrintQueue.PropertiesCollection

' Share the new printer using Remove/Add methods
Dim [shared] As New PrintBooleanProperty("IsShared", True)
myPrintProperties.Remove("IsShared")
myPrintProperties.Add("IsShared", [shared])

' Give the new printer its share name using SetProperty method
Dim theShareName As New PrintStringProperty("ShareName", """Son of " & sourcePrintQueue.Name & """")
myPrintProperties.SetProperty("ShareName", theShareName)

' Specify the physical location of the new printer using Remove/Add methods
Dim theLocation As New PrintStringProperty("Location", "the supply room")
myPrintProperties.Remove("Location")
myPrintProperties.Add("Location", theLocation)

' Specify the port for the new printer
Dim port() As String = { "COM1:" }


' Install the new printer on the local print server
Dim clonedPrinter As PrintQueue = myLocalPrintServer.InstallPrintQueue("My clone of " & sourcePrintQueue.Name, "Xerox WCP 35 PS", port, "WinPrint", myPrintProperties)
myLocalPrintServer.Commit()

' Report outcome
Console.WriteLine("{0} in {1} has been installed and shared as {2}", clonedPrinter.Name, clonedPrinter.Location, clonedPrinter.ShareName)
Console.WriteLine("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();

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

Комментарии

Коллекция имеет форму Hashtable словаря. Свойство Value каждого из них DictionaryEntry в коллекции — это экземпляр класса, производный от PrintProperty.

Конструкторы

Имя Описание
PrintPropertyDictionary()

Инициализирует новый экземпляр класса PrintPropertyDictionary.

PrintPropertyDictionary(SerializationInfo, StreamingContext)

Инициализирует новый экземпляр PrintPropertyDictionary класса и предоставляет его указанным SerializationInfo и StreamingContext.

Свойства

Имя Описание
comparer
Устаревшие..
Устаревшие..

Возвращает или задает используемый IComparer для параметра Hashtable.

(Унаследовано от Hashtable)
Count

Возвращает количество пар "ключ-значение", содержащихся в элементе Hashtable.

(Унаследовано от Hashtable)
EqualityComparer

Возвращает используемый IEqualityComparer для Hashtableпараметра .

(Унаследовано от Hashtable)
hcp
Устаревшие..
Устаревшие..

Возвращает или задает объект, который может выдавать хэш-коды.

(Унаследовано от Hashtable)
IsFixedSize

Возвращает значение, указывающее, имеет ли Hashtable размер фиксированного размера.

(Унаследовано от Hashtable)
IsReadOnly

Возвращает значение, указывающее, доступен ли доступ Hashtable только для чтения.

(Унаследовано от Hashtable)
IsSynchronized

Возвращает значение, указывающее, синхронизирован ли доступ к Hashtable синхронизированному (потокобезопасно).

(Унаследовано от Hashtable)
Item[Object]

Возвращает или задает значение, связанное с указанным ключом.

(Унаследовано от Hashtable)
Keys

Возвращает содержащий ICollection ключи в объекте Hashtable.

(Унаследовано от Hashtable)
SyncRoot

Получает объект, который можно использовать для синхронизации доступа к объекту Hashtable.

(Унаследовано от Hashtable)
Values

ICollection Возвращает значение, содержащее значения в объекте Hashtable.

(Унаследовано от Hashtable)

Методы

Имя Описание
Add(Object, Object)

Добавляет элемент с указанным ключом и значением в элемент Hashtable.

(Унаследовано от Hashtable)
Add(PrintProperty)

Добавляет указанный объект (класса, производный от PrintProperty) в словарь.

Clear()

Удаляет все элементы из элемента Hashtable.

(Унаследовано от Hashtable)
Clone()

Создает неглубокую копию Hashtable.

(Унаследовано от Hashtable)
Contains(Object)

Определяет, содержит ли Hashtable определенный ключ.

(Унаследовано от Hashtable)
ContainsKey(Object)

Определяет, содержит ли Hashtable определенный ключ.

(Унаследовано от Hashtable)
ContainsValue(Object)

Определяет, содержит ли Hashtable определенное значение.

(Унаследовано от Hashtable)
CopyTo(Array, Int32)

Копирует элементы в Hashtable одномерный Array экземпляр по указанному индексу.

(Унаследовано от Hashtable)
Dispose()

Освобождает все ресурсы, используемые этим элементом PrintPropertyDictionary.

Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые PrintPropertyDictionary и при необходимости освобождает управляемые ресурсы.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetEnumerator()

Возвращает значение IDictionaryEnumerator , которое выполняет итерацию через Hashtable.

(Унаследовано от Hashtable)
GetHash(Object)

Возвращает хэш-код для указанного ключа.

(Унаследовано от Hashtable)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetObjectData(SerializationInfo, StreamingContext)

Заполняет SerializationInfo данные, необходимые для сериализации PrintPropertyDictionary.

GetProperty(String)

Возвращает объект (класса, производный от PrintProperty) который представляет указанное свойство.

GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
KeyEquals(Object, Object)

Сравнивает определенный Object ключ с определенным ключом в элементе Hashtable.

(Унаследовано от Hashtable)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
OnDeserialization(Object)

ISerializable Реализует интерфейс и вызывает событие десериализации после завершения десериализации.

Remove(Object)

Удаляет элемент с указанным ключом из элемента Hashtable.

(Унаследовано от Hashtable)
SetProperty(String, PrintProperty)

Задает значение указанного атрибута объекту класса, производного от PrintProperty.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

Имя Описание
IEnumerable.GetEnumerator()

Возвращает перечислитель, который выполняет итерацию по коллекции.

(Унаследовано от Hashtable)

Методы расширения

Имя Описание
AsParallel(IEnumerable)

Включает параллелизацию запроса.

AsQueryable(IEnumerable)

Преобразует IEnumerable в IQueryable.

Cast<TResult>(IEnumerable)

Приведение элементов IEnumerable к указанному типу.

OfType<TResult>(IEnumerable)

Фильтрует элементы IEnumerable на основе указанного типа.

Применяется к