ObjRef Clase

Definición

Almacena toda la información relevante necesaria para generar un proxy y establecer comunicación con un objeto remoto.Stores all relevant information required to generate a proxy in order to communicate with a remote object.

public ref class ObjRef : System::Runtime::Serialization::IObjectReference, System::Runtime::Serialization::ISerializable
[System.Serializable]
public class ObjRef : System.Runtime.Serialization.IObjectReference, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ObjRef : System.Runtime.Serialization.IObjectReference, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Security.SecurityCritical]
public class ObjRef : System.Runtime.Serialization.IObjectReference, System.Runtime.Serialization.ISerializable
[<System.Serializable>]
type ObjRef = class
    interface IObjectReference
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ObjRef = class
    interface IObjectReference
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Security.SecurityCritical>]
type ObjRef = class
    interface IObjectReference
    interface ISerializable
Public Class ObjRef
Implements IObjectReference, ISerializable
Herencia
ObjRef
Atributos
Implementaciones

Ejemplos

En el ejemplo de código siguiente se muestra el uso de un personalizado ObjRef .The following code example demonstrates the use of a custom ObjRef. Para ver el código de activación que prueba el personalizado ObjRef , vea el ejemplo del RegisterWellKnownServiceType método.To view the activation code that tests the custom ObjRef, see the example for the RegisterWellKnownServiceType method.

// a custom ObjRef class that outputs its status
[System::Security::Permissions::SecurityPermissionAttribute(
   System::Security::Permissions::SecurityAction::Demand, 
   Flags=System::Security::Permissions::SecurityPermissionFlag::SerializationFormatter)]
[System::Security::Permissions::SecurityPermissionAttribute
(System::Security::Permissions::SecurityAction::Demand, 
Flags=System::Security::Permissions::SecurityPermissionFlag::Infrastructure)]	
[System::Security::Permissions::SecurityPermissionAttribute
(System::Security::Permissions::SecurityAction::InheritanceDemand, 
Flags=System::Security::Permissions::SecurityPermissionFlag::Infrastructure)]
public ref class MyObjRef: public ObjRef
{
private:

   // only instantiate using marshaling or deserialization
   MyObjRef(){}

public:
   MyObjRef( MarshalByRefObject^ o, Type^ t )
      : ObjRef( o, t )
   {
      Console::WriteLine( "Created MyObjRef." );
      ORDump();
   }

   MyObjRef( SerializationInfo^ i, StreamingContext c )
      : ObjRef( i, c )
   {
      Console::WriteLine( "Deserialized MyObjRef." );
   }

   virtual void GetObjectData( SerializationInfo^ s, StreamingContext c ) override
   {
      // After calling the base method, change the type from ObjRef to MyObjRef
      ObjRef::GetObjectData( s, c );
      s->SetType( GetType() );
      Console::WriteLine( "Serialized MyObjRef." );
   }

   virtual Object^ GetRealObject( StreamingContext context ) override
   {
      if ( IsFromThisAppDomain() || IsFromThisProcess() )
      {
         Console::WriteLine( "Returning actual Object^ referenced by MyObjRef." );
         return ObjRef::GetRealObject( context );
      }
      else
      {
         Console::WriteLine( "Returning proxy to remote Object^." );
         return RemotingServices::Unmarshal( this );
      }
   }

   void ORDump()
   {
      Console::WriteLine( " --- Reporting MyObjRef Info --- " );
      Console::WriteLine( "Reference to {0}.", TypeInfo->TypeName );
      Console::WriteLine( "URI is {0}.", URI );
      Console::WriteLine( "\nWriting EnvoyInfo: " );
      if ( EnvoyInfo != nullptr )
      {
         IMessageSink^ EISinks = EnvoyInfo->EnvoySinks;
         while ( EISinks != nullptr )
         {
            Console::WriteLine( "\tSink: {0}", EISinks );
            EISinks = EISinks->NextSink;
         }
      }
      else
            Console::WriteLine( "\t {no sinks}" );

      Console::WriteLine( "\nWriting ChannelInfo: " );
      for ( int i = 0; i < ChannelInfo->ChannelData->Length; i++ )
         Console::WriteLine( "\tChannel: {0}", ChannelInfo->ChannelData[ i ] );
      Console::WriteLine( " ----------------------------- " );
   }

};

// a class that uses MyObjRef
public ref class LocalObject: public MarshalByRefObject
{
public:

   // overriding CreateObjRef will allow us to return a custom ObjRef
   [System::Security::Permissions::SecurityPermissionAttribute
   (System::Security::Permissions::SecurityAction::LinkDemand,
   Flags=System::Security::Permissions::SecurityPermissionFlag::Infrastructure)]
   virtual ObjRef^ CreateObjRef( Type^ t ) override
   {
      return gcnew MyObjRef( this,t );
   }
};
// a custom ObjRef class that outputs its status
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public class MyObjRef : ObjRef {

   // only instantiate using marshaling or deserialization
   private MyObjRef() { }

   public MyObjRef(MarshalByRefObject o, Type t) : base(o, t)  {
      Console.WriteLine("Created MyObjRef.");
      ORDump();
   }

   public MyObjRef(SerializationInfo i, StreamingContext c) : base(i, c) {
      Console.WriteLine("Deserialized MyObjRef.");
   }

   public override void GetObjectData(SerializationInfo s, StreamingContext c) {
      // After calling the base method, change the type from ObjRef to MyObjRef
      base.GetObjectData(s, c);
      s.SetType(GetType());
      Console.WriteLine("Serialized MyObjRef.");
   }

   public override Object GetRealObject(StreamingContext context) {

      if ( IsFromThisAppDomain() || IsFromThisProcess() ) {
         Console.WriteLine("Returning actual object referenced by MyObjRef.");
         return base.GetRealObject(context);
      }
      else {
         Console.WriteLine("Returning proxy to remote object.");
         return RemotingServices.Unmarshal(this);
      }
   }

   public void ORDump() {

      Console.WriteLine(" --- Reporting MyObjRef Info --- ");
      Console.WriteLine("Reference to {0}.", TypeInfo.TypeName);
      Console.WriteLine("URI is {0}.", URI);
      Console.WriteLine("\nWriting EnvoyInfo: ");

      if ( EnvoyInfo != null) {

         IMessageSink EISinks = EnvoyInfo.EnvoySinks;
         while (EISinks != null) {
            Console.WriteLine("\tSink: " + EISinks.ToString());
            EISinks = EISinks.NextSink;
         }
      }
      else
        {
            Console.WriteLine("\t {no sinks}");
        }

        Console.WriteLine("\nWriting ChannelInfo: ");
      for (int i = 0; i < ChannelInfo.ChannelData.Length; i++)
         Console.WriteLine ("\tChannel: {0}", ChannelInfo.ChannelData[i]);
      Console.WriteLine(" ----------------------------- ");
   }
}

// a class that uses MyObjRef
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
public class LocalObject : MarshalByRefObject {
   // overriding CreateObjRef will allow us to return a custom ObjRef
   public override ObjRef CreateObjRef(Type t) {
      return new MyObjRef(this, t);
   }
}
' a custom ObjRef class that outputs its status
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
Public Class MyObjRef
   Inherits ObjRef

   ' only instantiate using marshaling or deserialization
   Private Sub New()
   End Sub

   Public Sub New(ByVal o As MarshalByRefObject, ByVal t As Type)
      MyBase.New(o, t)
      Console.WriteLine("Created MyObjRef.")
      ORDump()
   End Sub

   Public Sub New(ByVal i As SerializationInfo, ByVal c As StreamingContext)
      MyBase.New(i, c)
      Console.WriteLine("Deserialized MyObjRef.")
   End Sub

   Public Overrides Sub GetObjectData(ByVal s As SerializationInfo, ByVal c As StreamingContext)
      ' After calling the base method, change the type from ObjRef to MyObjRef
      MyBase.GetObjectData(s, c)
      s.SetType([GetType]())
      Console.WriteLine("Serialized MyObjRef.")
   End Sub

   Public Overrides Function GetRealObject(ByVal context As StreamingContext) As [Object]
      If IsFromThisAppDomain() Or IsFromThisProcess() Then
         Console.WriteLine("Returning actual object referenced by MyObjRef.")
         Return MyBase.GetRealObject(context)
      Else
         Console.WriteLine("Returning proxy to remote object.")
         Return RemotingServices.Unmarshal(Me)
      End If
   End Function

   Public Sub ORDump()
      Console.WriteLine(" --- Reporting MyObjRef Info --- ")
      Console.WriteLine("Reference to {0}.", TypeInfo.TypeName)
      Console.WriteLine("URI is {0}.", URI)

      Console.WriteLine(ControlChars.Cr + "Writing EnvoyInfo: ")
      If Not (EnvoyInfo Is Nothing) Then
         Dim EISinks As IMessageSink = EnvoyInfo.EnvoySinks
         Dim count As Integer = 0
         While Not (EISinks Is Nothing)
            Console.WriteLine(ControlChars.Tab + "Interated through sink #{0}", (count = count + 1))
            EISinks = EISinks.NextSink
         End While
      Else
         Console.WriteLine(ControlChars.Tab + " {no sinks}")
      End If
      Console.WriteLine(ControlChars.Cr + "Writing ChannelInfo: ")
      Dim i As Integer
      For i = 0 To ChannelInfo.ChannelData.Length - 1
         Console.WriteLine(ControlChars.Tab + "Channel: {0}", ChannelInfo.ChannelData(i))
      Next i
      Console.WriteLine(" ----------------------------- ")
   End Sub
   
End Class


' a class that uses MyObjRef
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
Public Class LocalObject
   Inherits MarshalByRefObject

   ' overriding CreateObjRef will allow us to return a custom ObjRef
   Public Overrides Function CreateObjRef(ByVal t As Type) As ObjRef
      Return New MyObjRef(Me, t)
   End Function

End Class

Comentarios

Un ObjRef es una representación serializable de un objeto que extiende MarshalByRefObject (MBR).A ObjRef is a serializable representation of an object that extends MarshalByRefObject (MBR). ObjRefSe utiliza para transferir una referencia de objeto a través de un AppDomain límite.A ObjRef is used to transfer an object reference across a AppDomain boundary. La creación ObjRef de un para un objeto se conoce como cálculo de referencias.Creating a ObjRef for an object is known as marshaling. Puede crear ObjRef (calcular las referencias a MarshalByRefObject ) explícitamente, registrando el objeto MBR con la infraestructura de comunicación remota (vea RemotingConfiguration y RemotingServices.Marshal ), o implícitamente, pasando un objeto MBR como parámetro al llamar a un objeto remoto.You can create a ObjRef (marshal a MarshalByRefObject) either explicitly, by registering the MBR object with the remoting infrastructure (see RemotingConfiguration and RemotingServices.Marshal), or implicitly, by passing an MBR object as a parameter when calling a remote object. La comunicación remota utiliza ObjRef objetos para almacenar y transmitir toda la información relevante sobre el MarshalByRefObject que se va a usar de forma remota.Remoting uses ObjRef objects to store and transmit all the relevant information about the MarshalByRefObject being remoted.

ObjRefContiene información que describe la Type clase y del objeto cuyas referencias se van a calcular, su ubicación exacta e información relacionada con la comunicación sobre cómo llegar a la subdivisión remota en la que se encuentra el objeto.The ObjRef contains information that describes the Type and class of the object being marshaled, its exact location, and communication-related information on how to reach the remoting subdivision where the object is located.

Después MarshalByRefObject de calcular las referencias de una clase que implementa, el ObjRef que representa se transfiere a través de un canal a otro dominio de aplicación, posiblemente en otro proceso o equipo.After a class implementing MarshalByRefObject is marshaled, the ObjRef that represents it is transferred through a channel into another application domain, possibly in another process or computer. Cuando ObjRef se deserializa (vea serialización XML y SOAP) en el dominio de aplicación de destino, se analiza para crear un proxy transparente para el objeto MBR remoto.When the ObjRef is deserialized (see XML and SOAP Serialization) in the target application domain, it is parsed to create a transparent proxy for the remote MBR object. Esta operación se conoce como anulación de la serialización.This operation is known as unmarshaling.

Un proxy transparente es un objeto que proporciona la ilusión de que el objeto real Reside en el espacio del cliente.A transparent proxy is an object that provides the illusion that the actual object resides in the client's space. Logra esto mediante el reenvío de las llamadas realizadas en el objeto real mediante la infraestructura de comunicación remota.It achieves this by forwarding calls made on it to the real object using the remoting infrastructure. El proxy transparente se hospeda en una instancia de una clase de tipo en tiempo de ejecución administrada RealProxy .The transparent proxy is itself housed by an instance of a managed run-time class of type RealProxy. RealProxyImplementa una parte de la funcionalidad necesaria para reenviar las operaciones desde el proxy transparente.The RealProxy implements a part of the functionality needed to forward the operations from the transparent proxy.

Un objeto proxy se puede usar sin tener en cuenta las subdivisiones de comunicación remota dentro de AppDomain .A proxy object can be used without regard to any remoting subdivisions within a AppDomain. Las aplicaciones no necesitan distinguir entre las referencias de proxy y las referencias de objeto.Applications need not distinguish between proxy references and object references. Sin embargo, los proveedores de servicios que se ocupan de problemas como la activación, la administración de la duración y las transacciones deben hacer tales diferencias.However, service providers dealing with issues such as activation, lifetime management, and transactions need to make such distinctions.

Esta clase realiza una petición de vínculo y una petición de herencia en el nivel de clase.This class makes a link demand and an inheritance demand at the class level. SecurityExceptionSe produce una excepción cuando el llamador inmediato o la clase derivada no tienen permiso de infraestructura.A SecurityException is thrown when either the immediate caller or the derived class does not have infrastructure permission. Para obtener más información sobre las demandas de seguridad, consulte peticiones de vínculo y peticiones de herencia.For details about security demands, see Link Demands and Inheritance Demands.

Constructores

ObjRef()

Inicializa una nueva instancia de la clase ObjRef con valores predeterminados.Initializes a new instance of the ObjRef class with default values.

ObjRef(MarshalByRefObject, Type)

Inicializa una nueva instancia de la clase ObjRef para hacer referencia a un MarshalByRefObject especificado de un Type dado.Initializes a new instance of the ObjRef class to reference a specified MarshalByRefObject of a specified Type.

ObjRef(SerializationInfo, StreamingContext)

Inicializa una nueva instancia de la clase ObjRef a partir de datos serializados.Initializes a new instance of the ObjRef class from serialized data.

Propiedades

ChannelInfo

Obtiene o establece el objeto IChannelInfo para ObjRef.Gets or sets the IChannelInfo for the ObjRef.

EnvoyInfo

Obtiene o establece el objeto IEnvoyInfo para ObjRef.Gets or sets the IEnvoyInfo for the ObjRef.

TypeInfo

Obtiene o establece IRemotingTypeInfo para el objeto que ObjRef describe.Gets or sets the IRemotingTypeInfo for the object that the ObjRef describes.

URI

Obtiene o establece el identificador URI de la instancia de objeto especificada.Gets or sets the URI of the specific object instance.

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.Determines whether the specified object is equal to the current object.

(Heredado de Object)
GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Heredado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Rellena un objeto SerializationInfo especificado con los datos necesarios para serializar la instancia de ObjRef actual.Populates a specified SerializationInfo with the data needed to serialize the current ObjRef instance.

GetRealObject(StreamingContext)

Devuelve una referencia al objeto remoto que ObjRef describe.Returns a reference to the remote object that the ObjRef describes.

GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Heredado de Object)
IsFromThisAppDomain()

Devuelve un valor booleano que indica si la instancia de ObjRef actual hace referencia a un objeto ubicado en el objeto AppDomain actual.Returns a Boolean value that indicates whether the current ObjRef instance references an object located in the current AppDomain.

IsFromThisProcess()

Devuelve un valor booleano que indica si la instancia de ObjRef actual hace referencia a un objeto ubicado en el proceso actual.Returns a Boolean value that indicates whether the current ObjRef instance references an object located in the current process.

MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Heredado de Object)

Se aplica a

Consulte también