OutAttribute Classe
Definição
Indica que os dados devem passar por marshaling do receptor de volta ao chamador.Indicates that data should be marshaled from callee back to caller.
public ref class OutAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Parameter, Inherited=false)]
public sealed class OutAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Parameter, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class OutAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Parameter, Inherited=false)>]
type OutAttribute = class
inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Parameter, Inherited=false)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type OutAttribute = class
inherit Attribute
Public NotInheritable Class OutAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
O exemplo a seguir mostra como aplicar o InAttribute e o OutAttribute a um protótipo de invocação de plataforma que passa uma matriz como um parâmetro.The following example shows how to apply the InAttribute and OutAttribute to a platform invoke prototype that passes an array as a parameter. A combinação de atributos direcional permite que o chamador Veja as alterações feitas pelo receptor.The combination of directional attributes allows the caller to see the changes made by the callee.
using namespace System;
using namespace System::Runtime::InteropServices;
// Declare a class member for each structure element.
[StructLayout(LayoutKind::Sequential, CharSet = CharSet::Unicode)]
public ref class OpenFileName
{
public:
int structSize;
String^ filter;
String^ file;
// ...
};
private ref class NativeMethods
{
public:
// Declare a managed prototype for the unmanaged function.
[DllImport("Comdlg32.dll", CharSet = CharSet::Unicode)]
static bool GetOpenFileName([In, Out]OpenFileName^ ofn);
};
void main() {}
using System.Runtime.InteropServices;
using System;
// Declare a class member for each structure element.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class OpenFileName
{
public int structSize = 0;
public string filter = null;
public string file = null;
// ...
}
internal static class NativeMethods
{
// Declare a managed prototype for the unmanaged function.
[DllImport("Comdlg32.dll", CharSet = CharSet.Unicode)]
internal static extern bool GetOpenFileName([In, Out] OpenFileName ofn);
}
public class MainMethod
{
static void Main()
{ }
}
Imports System.Runtime.InteropServices
' Declare a class member for each structure element.
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)>
Public Class OpenFileName
Public structSize As Integer = 0
Public filter As String = Nothing
Public file As String = Nothing
' ...
End Class
Friend Class NativeMethods
' Declare managed prototype for the unmanaged function.
Friend Declare Unicode Function GetOpenFileName Lib "Comdlg32.dll" (
<[In](), Out()> ByVal ofn As OpenFileName) As Boolean
End Class
Public Class App
Public Shared Sub Main()
End Sub
End Class
Comentários
Você pode aplicar esse atributo a parâmetros.You can apply this attribute to parameters.
O OutAttribute é opcional.The OutAttribute is optional. O atributo tem suporte somente para a interoperabilidade COM e a invocação de plataforma.The attribute is supported for COM interop and platform invoke only. Na ausência de configurações explícitas, o Interop marshaler assume regras com base no tipo de parâmetro, se o parâmetro é passado por referência ou por valor, e se o tipo é blittable ou não blittable.In the absence of explicit settings, the interop marshaler assumes rules based on the parameter type, whether the parameter is passed by reference or by value, and whether the type is blittable or non-blittable. Por exemplo, a StringBuilder classe é sempre presumida como entrada/saída e uma matriz de cadeias de caracteres passada por valor é considerada como em.For example, the StringBuilder class is always assumed to be In/Out and an array of strings passed by value is assumed to be In.
O comportamento somente out nunca é um comportamento de marshaling padrão para parâmetros.Out-only behavior is never a default marshaling behavior for parameters. Você pode aplicar o OutAttribute valor de para e os tipos de referência passados por referência para alterar o comportamento de entrada/saída para comportamento somente de saída, o que equivale a usar a out palavra-chave em C#.You can apply the OutAttribute to value and reference types passed by reference to change In/Out behavior to Out-only behavior, which is equivalent to using the out keyword in C#. Por exemplo, as matrizes passadas por valor, com marshaling como parâmetros somente no, por padrão, podem ser alteradas para out-only.For example, arrays passed by value, marshaled as In-only parameters by default, can be changed to Out-only. No entanto, o comportamento nem sempre fornece a semântica esperada quando os tipos incluem todos os elementos ou campos de transferência de bits, pois o marshaling de interoperabilidade usa fixação.However, the behavior does not always provide expected semantics when the types include all-blittable elements or fields because the interop marshaler uses pinning. Se você não se importa com a passagem de dados para o receptor, o marshaling somente out pode fornecer um melhor desempenho para tipos não blittable.If you do not care about passing data into the callee, Out-only marshaling can provide better performance for non-blittable types.
Combinar o InAttribute e o OutAttribute é particularmente útil quando aplicado a matrizes e tipos formatados e não blittable.Combining the InAttribute and OutAttribute is particularly useful when applied to arrays and formatted, non-blittable types. Os chamadores veem as alterações que um receptor faz para esses tipos somente quando você aplica ambos os atributos.Callers see the changes a callee makes to these types only when you apply both attributes. Como esses tipos exigem cópia durante o marshaling, você pode usar InAttribute e OutAttribute para reduzir cópias desnecessárias.Since these types require copying during marshaling, you can use InAttribute and OutAttribute to reduce unnecessary copies.
Para obter mais informações sobre o efeito do OutAttribute comportamento de marshaling, consulte atributos direcionais.For more information on the effect of OutAttribute on marshaling behavior, see Directional Attributes.
Construtores
| OutAttribute() |
Inicializa uma nova instância da classe OutAttribute.Initializes a new instance of the OutAttribute class. |
Propriedades
| TypeId |
Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute. (Herdado de Attribute) |
Métodos
| Equals(Object) |
Retorna um valor que indica se essa instância é igual a um objeto especificado.Returns a value that indicates whether this instance is equal to a specified object. (Herdado de Attribute) |
| GetHashCode() |
Retorna o código hash para a instância.Returns the hash code for this instance. (Herdado de Attribute) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (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.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (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.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Herdado de Attribute) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (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.Maps a set of names to a corresponding set of dispatch identifiers. (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.Retrieves the type information for an object, which can be used to get the type information for an 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).Retrieves the number of type information interfaces that an object provides (either 0 or 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.Provides access to properties and methods exposed by an object. (Herdado de Attribute) |