ServiceKnownTypeAttribute Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Указывает известные типы, используемые службой при сериализации или десериализации.
public ref class ServiceKnownTypeAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface | System.AttributeTargets.Method, AllowMultiple=true, Inherited=true)]
public sealed class ServiceKnownTypeAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface | System.AttributeTargets.Method, AllowMultiple=true, Inherited=true)>]
type ServiceKnownTypeAttribute = class
inherit Attribute
Public NotInheritable Class ServiceKnownTypeAttribute
Inherits Attribute
- Наследование
- Атрибуты
Примеры
В следующем примере атрибут применяется ServiceKnownTypeAttribute к интерфейсу, в котором атрибут задает имя метода и декларативный тип.
// Define a service contract and apply the ServiceKnownTypeAttribute
// to specify types to include when generating client code.
// The types must have the DataContractAttribute and DataMemberAttribute
// applied to be serialized and deserialized. The attribute specifies the
// name of a method (GetKnownTypes) in a class (Helper) defined below.
[ServiceKnownType("GetKnownTypes", typeof(Helper))]
[ServiceContract()]
public interface ICatalog
{
// Any object type can be inserted into a Hashtable. The
// ServiceKnownTypeAttribute allows you to include those types
// with the client code.
[OperationContract]
Hashtable GetItems();
}
// This class has the method named GetKnownTypes that returns a generic IEnumerable.
static class Helper
{
public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
{
System.Collections.Generic.List<System.Type> knownTypes =
new System.Collections.Generic.List<System.Type>();
// Add any types to include here.
knownTypes.Add(typeof(Widget));
knownTypes.Add(typeof(Machine));
return knownTypes;
}
}
[DataContract()]
public class Widget
{
[DataMember]
public string Id;
[DataMember]
public string Catalog;
}
[DataContract()]
public class Machine : Widget
{
[DataMember]
public string Maker;
}
' Define a service contract and apply the ServiceKnownTypeAttribute
' to specify types to include when generating client code.
' The types must have the DataContractAttribute and DataMemberAttribute
' applied to be serialized and deserialized. The attribute specifies the
' name of a method (GetKnownTypes) in a class (Helper) defined below.
<ServiceKnownType("GetKnownTypes", GetType(Helper)), ServiceContract()> _
Public Interface ICalculator
' Any object type can be inserted into a Hashtable. The
' ServiceKnownTypeAttribute allows you to include those types
' with the client code.
<OperationContract()> _
Function GetItems() As Hashtable
End Interface
' This class has the method named GetKnownTypes that returns a generic IEnumerable.
Friend Class Helper
Public Shared Function GetKnownTypes(provider As ICustomAttributeProvider) _
As IEnumerable(of Type)
Dim knownTypes As List(Of Type) = New List(Of Type)
' Add any types to include here.
knownTypes.Add(GetType(Widget))
knownTypes.Add(GetType(Machine))
Return knownTypes
End Function
End Class
<DataContract()> _
Public Class Widget
<DataMember()> _
Public Id As String
<DataMember()> _
Public Catalog As String
End Class
<DataContract()> _
Public Class Machine
Inherits Widget
<DataMember()> _
Public Maker As String
End Class
Кроме того, примените атрибут к интерфейсу, указывая известный тип для включения.
// Apply the ServiceKnownTypeAttribute to the
// interface specifying the type to include. Apply
// the attribute more than once if needed.
[ServiceKnownType(typeof(Widget))]
[ServiceKnownType(typeof(Machine))]
[ServiceContract()]
public interface ICatalog2
{
// Any object type can be inserted into a Hashtable. The
// ServiceKnownTypeAttribute allows you to include those types
// with the client code.
[OperationContract]
Hashtable GetItems();
}
' Apply the ServiceKnownTypeAttribute to the
' interface specifying the type to include. Apply the attribute
' more than once, if needed.
<ServiceKnownType(GetType(Widget)), ServiceKnownType(GetType(Machine)), _
ServiceContract()> _
Public Interface ICalculator2
' Any object type can be inserted into a Hashtable. The
' ServiceKnownTypeAttribute allows you to include those types
' with the client code.
<OperationContract()> _
Function GetItems() As Hashtable
End Interface
Комментарии
Он ServiceKnownTypeAttribute предназначен для использования при создании контрактов служб Windows Communication Foundation (WCF) (интерфейсов, определяющих службу и его методы). Известные типы — это типы, которые могут присутствовать в графе объектов при сериализации или десериализации. Дополнительные сведения об известных типах см. в известных типов контракта данных.
Чтобы использовать MethodName свойство, создайте класс, содержащий метод (или методы), который возвращает массив типов (каждый из которых является известным типом). При применении атрибута задайте methodName имя метода, который возвращает список типов и задает declaringType тип, содержащий метод. Метод должен возвращать тип, реализующий IEnumerable<T> интерфейс. Метод также должен включать параметр типа ICustomAttributeProvider.
Атрибут можно применять несколько раз к интерфейсу, классу или методу при каждом указании нового известного типа.
Замечание
Вы можете использовать слово ServiceKnownType в коде Microsoft Visual Basic или C# вместо более длинного ServiceKnownTypeAttribute.
Конструкторы
| Имя | Описание |
|---|---|
| ServiceKnownTypeAttribute(String, Type) |
Инициализирует новый экземпляр ServiceKnownTypeAttribute класса с именем метода, возвращающего известные типы и тип, содержащий метод (или методы), возвращающий известные типы. |
| ServiceKnownTypeAttribute(String) |
Инициализирует новый экземпляр ServiceKnownTypeAttribute класса и задает имя метода, возвращающего известные типы. |
| ServiceKnownTypeAttribute(Type) |
Инициализирует новый экземпляр ServiceKnownTypeAttribute класса с указанным известным типом. |
Свойства
| Имя | Описание |
|---|---|
| DeclaringType |
Возвращает тип, содержащий методы, возвращающие известные типы. |
| MethodName |
Возвращает имя метода, возвращающего коллекцию известных типов. |
| Type |
Известный тип, который можно включить в граф объектов. |
| TypeId |
При реализации в производном классе получает уникальный идентификатор для этого Attribute. (Унаследовано от Attribute) |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Возвращает значение, указывающее, равен ли этот экземпляр указанному объекту. (Унаследовано от Attribute) |
| GetHashCode() |
Возвращает хэш-код для этого экземпляра. (Унаследовано от Attribute) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| IsDefaultAttribute() |
При переопределении в производном классе указывает, является ли значение этого экземпляра значением по умолчанию для производного класса. (Унаследовано от Attribute) |
| Match(Object) |
При переопределении в производном классе возвращает значение, указывающее, равен ли этот экземпляр указанному объекту. (Унаследовано от Attribute) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |
Явные реализации интерфейса
| Имя | Описание |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации. (Унаследовано от Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Извлекает сведения о типе объекта, который можно использовать для получения сведений о типе для интерфейса. (Унаследовано от Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1). (Унаследовано от Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Предоставляет доступ к свойствам и методам, предоставляемым объектом. (Унаследовано от Attribute) |