ServiceKnownTypeAttribute Classe

Definição

Especifica tipos conhecidos a serem usados por um serviço ao serializar ou desserializar.

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
Herança
ServiceKnownTypeAttribute
Atributos

Exemplos

O exemplo a seguir aplica o ServiceKnownTypeAttribute atributo a uma interface em que o atributo especifica um nome de método e um tipo de declaração.

// 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

Como alternativa, aplique o atributo à interface que especifica o tipo conhecido a ser incluído.

// 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

Comentários

O ServiceKnownTypeAttribute objetivo é usar ao criar contratos de serviço do WCF (Windows Communication Foundation) (interfaces que definem o serviço e seus métodos). Os tipos conhecidos são tipos que podem estar presentes em um grafo de objeto quando ocorre a serialização ou desserialização. Para obter mais informações sobre tipos conhecidos, consulte Tipos Conhecidos do Contrato de Dados.

Para usar a MethodName propriedade, crie uma classe que contenha um método (ou métodos) que retorna uma matriz de tipos (cada um sendo um tipo conhecido). Ao aplicar o atributo, defina o methodName nome de um método que retorna a lista de tipos e defina o declaringType tipo que contém o método. O método deve retornar um tipo que implemente a IEnumerable<T> interface. O método também deve incluir um parâmetro do tipo ICustomAttributeProvider.

Você também pode aplicar o atributo várias vezes a uma interface, classe ou método, sempre que especificar um novo tipo conhecido.

Observação

Você pode usar a palavra ServiceKnownType em seu código microsoft Visual Basic ou C# em vez de mais tempoServiceKnownTypeAttribute.

Construtores

ServiceKnownTypeAttribute(String)

Inicializa uma nova instância da classe ServiceKnownTypeAttribute e especifica o nome de um método que retorna os tipos conhecidos.

ServiceKnownTypeAttribute(String, Type)

Inicializa uma nova instância da classe ServiceKnownTypeAttribute com o nome de um método que retorna os tipos conhecidos e o tipo que contém o método (ou métodos) que retorna os tipos conhecidos.

ServiceKnownTypeAttribute(Type)

Inicializa uma nova instância da classe ServiceKnownTypeAttribute com o tipo conhecido especificado.

Propriedades

DeclaringType

Obtém o tipo que contém os métodos que retornam os tipos conhecidos.

MethodName

Obtém o nome de um método que retorna a coleção de tipos conhecidos.

Type

O tipo conhecido que pode ser incluído em um grafo de objeto.

TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.

(Herdado de Attribute)

Métodos

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()

Retorna o código hash para a instância.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Confira também