AppDomain.CreateInstanceAndUnwrap AppDomain.CreateInstanceAndUnwrap AppDomain.CreateInstanceAndUnwrap AppDomain.CreateInstanceAndUnwrap Method

Definición

Crea una nueva instancia del tipo especificado.Creates a new instance of a specified type.

Sobrecargas

CreateInstanceAndUnwrap(String, String) CreateInstanceAndUnwrap(String, String) CreateInstanceAndUnwrap(String, String) CreateInstanceAndUnwrap(String, String)

Crea una nueva instancia del tipo especificado.Creates a new instance of the specified type. Los parámetros especifican el ensamblado en el que se definen el tipo y el nombre del tipo.Parameters specify the assembly where the type is defined, and the name of the type.

CreateInstanceAndUnwrap(String, String, Object[]) CreateInstanceAndUnwrap(String, String, Object[]) CreateInstanceAndUnwrap(String, String, Object[]) CreateInstanceAndUnwrap(String, String, Object[])

Crea una nueva instancia del tipo especificado.Creates a new instance of the specified type. Los parámetros especifican el ensamblado en el que se definen el tipo, el nombre del tipo y una matriz de atributos de activación.Parameters specify the assembly where the type is defined, the name of the type, and an array of activation attributes.

CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Crea una nueva instancia del tipo especificado definido en el ensamblado indicado, especificando si se pasa por alto el modelo de mayúsculas y minúsculas del nombre de tipo, los atributos de enlace y el enlazador que se usan para seleccionar el tipo que se va a crear, los argumentos del constructor, la referencia cultural y los atributos de activación.Creates a new instance of the specified type defined in the specified assembly, specifying whether the case of the type name is ignored; the binding attributes and the binder that are used to select the type to be created; the arguments of the constructor; the culture; and the activation attributes.

CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

Crea una nueva instancia del tipo especificado.Creates a new instance of the specified type. Los parámetros especifican el nombre del tipo, así como la forma en que se encontró y se creó.Parameters specify the name of the type, and how it is found and created.

CreateInstanceAndUnwrap(String, String) CreateInstanceAndUnwrap(String, String) CreateInstanceAndUnwrap(String, String) CreateInstanceAndUnwrap(String, String)

Crea una nueva instancia del tipo especificado.Creates a new instance of the specified type. Los parámetros especifican el ensamblado en el que se definen el tipo y el nombre del tipo.Parameters specify the assembly where the type is defined, and the name of the type.

public:
 System::Object ^ CreateInstanceAndUnwrap(System::String ^ assemblyName, System::String ^ typeName);
public object CreateInstanceAndUnwrap (string assemblyName, string typeName);
member this.CreateInstanceAndUnwrap : string * string -> obj
Public Function CreateInstanceAndUnwrap (assemblyName As String, typeName As String) As Object

Parámetros

assemblyName
String String String String

Nombre para mostrar del ensamblado.The display name of the assembly. Vea FullName.See FullName.

typeName
String String String String

Nombre completo del tipo solicitado, incluido el espacio de nombres, pero no el ensamblado, tal y como lo devuelve la propiedad FullName.The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

Devoluciones

Instancia del objeto especificado por typeName.An instance of the object specified by typeName.

Excepciones

assemblyName o typeName es null.assemblyName or typeName is null.

No se encontró ningún constructor público coincidente.No matching public constructor was found.

No se encontró typename en assemblyName.typename was not found in assemblyName.

No se encontró assemblyName.assemblyName was not found.

El llamador no tiene permiso para llamar a este constructor.The caller does not have permission to call this constructor.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

assemblyName no es un ensamblado válido.assemblyName is not a valid assembly.

-o bien--or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y assemblyName se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyName was compiled with a later version.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Ejemplos

El ejemplo de código siguiente muestra la manera más sencilla para ejecutar código en otro dominio de aplicación.The following code example shows the simplest way to execute code in another application domain. El ejemplo define una clase denominada Worker que hereda de MarshalByRefObject.The example defines a class named Worker that inherits from MarshalByRefObject. La Worker clase define un método que muestra el nombre del dominio de aplicación en el que se está ejecutando.The Worker class defines a method that displays the name of the application domain in which it is executing. El ejemplo crea instancias de Worker en el dominio de aplicación predeterminado y en un dominio de aplicación.The example creates instances of Worker in the default application domain and in a new application domain.

Nota

El ensamblado que contiene Worker deben cargarse en ambos dominios de aplicación, pero se pueden cargar otros ensamblados que solo existen en el nuevo dominio de aplicación.The assembly that contains Worker must be loaded into both application domains, but it can load other assemblies that exist only in the new application domain.

using namespace System;
using namespace System::Reflection;

public ref class Worker : MarshalByRefObject
{
public:
    void PrintDomain() 
    { 
        Console::WriteLine("Object is executing in AppDomain \"{0}\"",
            AppDomain::CurrentDomain->FriendlyName); 
    }
};
 
void main()
{
    // Create an ordinary instance in the current AppDomain
    Worker^ localWorker = gcnew Worker();
    localWorker->PrintDomain();
 
    // Create a new application domain, create an instance
    // of Worker in the application domain, and execute code
    // there.
    AppDomain^ ad = AppDomain::CreateDomain("New domain");
    Worker^ remoteWorker = (Worker^) ad->CreateInstanceAndUnwrap(
        Worker::typeid->Assembly->FullName,
        "Worker");
    remoteWorker->PrintDomain();
}

/* This code produces output similar to the following:

Object is executing in AppDomain "source.exe"
Object is executing in AppDomain "New domain"
 */
using System;
using System.Reflection;
 
public class Worker : MarshalByRefObject
{
    public void PrintDomain() 
    { 
        Console.WriteLine("Object is executing in AppDomain \"{0}\"",
            AppDomain.CurrentDomain.FriendlyName); 
    }
}
 
class Example
{
    public static void Main()
    {
        // Create an ordinary instance in the current AppDomain
        Worker localWorker = new Worker();
        localWorker.PrintDomain();
 
        // Create a new application domain, create an instance
        // of Worker in the application domain, and execute code
        // there.
        AppDomain ad = AppDomain.CreateDomain("New domain");
        Worker remoteWorker = (Worker) ad.CreateInstanceAndUnwrap(
            typeof(Worker).Assembly.FullName,
            "Worker");
        remoteWorker.PrintDomain();
    }
}

/* This code produces output similar to the following:

Object is executing in AppDomain "source.exe"
Object is executing in AppDomain "New domain"
 */
Imports System.Reflection

Public Class Worker
    Inherits MarshalByRefObject
    
    Public Sub PrintDomain() 
        Console.WriteLine("Object is executing in AppDomain ""{0}""", _
            AppDomain.CurrentDomain.FriendlyName)
    End Sub 
End Class 

Class Example
    
    Public Shared Sub Main() 
        ' Create an ordinary instance in the current AppDomain
        Dim localWorker As New Worker()
        localWorker.PrintDomain()
        
        ' Create a new application domain, create an instance
        ' of Worker in the application domain, and execute code
        ' there.
        Dim ad As AppDomain = AppDomain.CreateDomain("New domain")
        Dim remoteWorker As Worker = CType( _
            ad.CreateInstanceAndUnwrap( _
                GetType(Worker).Assembly.FullName, _
                "Worker"), _
            Worker)
        remoteWorker.PrintDomain()
    
    End Sub 
End Class 

' This code produces output similar to the following:
'
'Object is executing in AppDomain "source.exe"
'Object is executing in AppDomain "New domain"

Comentarios

Se trata de un método de conveniencia que combina CreateInstance y ObjectHandle.Unwrap.This is a convenience method that combines CreateInstance and ObjectHandle.Unwrap. Este método llama al constructor predeterminado para typeName.This method calls the default constructor for typeName.

Consulte AssemblyName de formato de assemblyName.See AssemblyName for the format of assemblyName. Consulte la Type.FullName propiedad de formato de typeName.See the Type.FullName property for the format of typeName.

Nota

Si realiza una llamada enlazada a un método M de un objeto de tipo T1 que devolvió CreateInstanceAndUnwrap, y que el método realiza una llamada enlazada a un método de un objeto de tipo T2 en un ensamblado C distinto el ensamblado actual o el ensamblado que contiene T1, ensamblado C se carga en el dominio de aplicación actual.If you make an early-bound call to a method M of an object of type T1 that was returned by CreateInstanceAndUnwrap, and that method makes an early-bound call to a method of an object of type T2 in an assembly C other than the current assembly or the assembly containing T1, assembly C is loaded into the current application domain. Esta carga se produce incluso si el enlace anticipado llamada a T1.M() se realizó en el cuerpo de un DynamicMethod, o en otro código generado dinámicamente.This loading occurs even if the early-bound call to T1.M() was made in the body of a DynamicMethod, or in other dynamically generated code. Si el dominio actual es el dominio predeterminado, el ensamblado C no se puede descargar hasta que finaliza el proceso.If the current domain is the default domain, assembly C cannot be unloaded until the process ends. Si más adelante, el dominio actual intenta cargar el ensamblado C, podría producir un error en la carga.If the current domain later attempts to load assembly C, the load might fail.

Seguridad

FileIOPermissionAccess
Para poder leer el archivo que contiene el manifiesto del ensamblado, o si va a crear un tipo desde un módulo que no sea el archivo de manifiesto.for the ability to read the file containing the assembly manifest, or if you are creating a type from a module other than the manifest file. Enumeración asociada: ReadAssociated enumeration: Read

WebPermission
Para poder acceder a la ubicación del ensamblado si el ensamblado no es local.for the ability to access the location of the assembly if the assembly is not local.

Consulte también:

CreateInstanceAndUnwrap(String, String, Object[]) CreateInstanceAndUnwrap(String, String, Object[]) CreateInstanceAndUnwrap(String, String, Object[]) CreateInstanceAndUnwrap(String, String, Object[])

Crea una nueva instancia del tipo especificado.Creates a new instance of the specified type. Los parámetros especifican el ensamblado en el que se definen el tipo, el nombre del tipo y una matriz de atributos de activación.Parameters specify the assembly where the type is defined, the name of the type, and an array of activation attributes.

public:
 System::Object ^ CreateInstanceAndUnwrap(System::String ^ assemblyName, System::String ^ typeName, cli::array <System::Object ^> ^ activationAttributes);
public object CreateInstanceAndUnwrap (string assemblyName, string typeName, object[] activationAttributes);
member this.CreateInstanceAndUnwrap : string * string * obj[] -> obj
Public Function CreateInstanceAndUnwrap (assemblyName As String, typeName As String, activationAttributes As Object()) As Object

Parámetros

assemblyName
String String String String

Nombre para mostrar del ensamblado.The display name of the assembly. Vea FullName.See FullName.

typeName
String String String String

Nombre completo del tipo solicitado, incluido el espacio de nombres, pero no el ensamblado, tal y como lo devuelve la propiedad FullName.The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

activationAttributes
Object[]

Matriz de uno o más atributos que puede participar en la activación.An array of one or more attributes that can participate in activation. Normalmente, una matriz que contiene un único objeto UrlAttribute que especifica la dirección URL necesaria para activar un objeto remoto.Typically, an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

Este parámetro está relacionado con los objetos activados por el cliente. La activación por parte del cliente es una tecnología heredada que se conserva para la compatibilidad con versiones anteriores, pero no se recomienda para nuevo desarrollo.This parameter is related to client-activated objects.Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Las aplicaciones distribuidas deberían usar Windows Communication Foundation.Distributed applications should instead use Windows Communication Foundation.

Devoluciones

Instancia del objeto especificado por typeName.An instance of the object specified by typeName.

Excepciones

assemblyName o typeName es null.assemblyName or typeName is null.

No se encontró ningún constructor público coincidente.No matching public constructor was found.

No se encontró typename en assemblyName.typename was not found in assemblyName.

No se encontró assemblyName.assemblyName was not found.

El llamador no tiene permiso para llamar a este constructor.The caller does not have permission to call this constructor.

El llamador no puede ofrecer atributos de activación para un objeto que no hereda de MarshalByRefObject.The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

assemblyName no es un ensamblado válido.assemblyName is not a valid assembly.

-o bien--or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y assemblyName se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyName was compiled with a later version.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Ejemplos

using namespace System;
using namespace System::IO;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Runtime::Remoting;

ref class ADDyno
{
public:
   static Type^ CreateADynamicAssembly( interior_ptr<AppDomain^> myNewDomain, String^ executableNameNoExe )
   {
      String^ executableName = String::Concat( executableNameNoExe, ".exe" );
      AssemblyName^ myAsmName = gcnew AssemblyName;
      myAsmName->Name = executableNameNoExe;
      myAsmName->CodeBase = Environment::CurrentDirectory;
      AssemblyBuilder^ myAsmBuilder = ( *myNewDomain)->DefineDynamicAssembly( myAsmName, AssemblyBuilderAccess::RunAndSave );
      Console::WriteLine( "-- Dynamic Assembly instantiated." );
      ModuleBuilder^ myModBuilder = myAsmBuilder->DefineDynamicModule( executableNameNoExe, executableName );
      TypeBuilder^ myTypeBuilder = myModBuilder->DefineType( executableNameNoExe, TypeAttributes::Public, MarshalByRefObject::typeid );
      array<Type^>^temp0 = nullptr;
      MethodBuilder^ myFCMethod = myTypeBuilder->DefineMethod( "CountLocalFiles", static_cast<MethodAttributes>(MethodAttributes::Public | MethodAttributes::Static), nullptr, temp0 );
      MethodInfo^ currentDirGetMI = Environment::typeid->GetProperty( "CurrentDirectory" )->GetGetMethod();
      array<Type^>^temp1 = {String::typeid};
      MethodInfo^ writeLine0objMI = Console::typeid->GetMethod( "WriteLine", temp1 );
      array<Type^>^temp2 = {String::typeid,Object::typeid,Object::typeid};
      MethodInfo^ writeLine2objMI = Console::typeid->GetMethod( "WriteLine", temp2 );
      array<Type^>^temp3 = {String::typeid};
      MethodInfo^ getFilesMI = Directory::typeid->GetMethod( "GetFiles", temp3 );
      myFCMethod->InitLocals = true;
      ILGenerator^ myFCIL = myFCMethod->GetILGenerator();
      Console::WriteLine( "-- Generating MSIL method body..." );
      LocalBuilder^ v0 = myFCIL->DeclareLocal( String::typeid );
      LocalBuilder^ v1 = myFCIL->DeclareLocal( int::typeid );
      LocalBuilder^ v2 = myFCIL->DeclareLocal( String::typeid );
      LocalBuilder^ v3 = myFCIL->DeclareLocal( array<String^>::typeid );
      Label evalForEachLabel = myFCIL->DefineLabel();
      Label topOfForEachLabel = myFCIL->DefineLabel();

      // Build the method body.
      myFCIL->EmitCall( OpCodes::Call, currentDirGetMI, nullptr );
      myFCIL->Emit( OpCodes::Stloc_S, v0 );
      myFCIL->Emit( OpCodes::Ldc_I4_0 );
      myFCIL->Emit( OpCodes::Stloc_S, v1 );
      myFCIL->Emit( OpCodes::Ldstr, "---" );
      myFCIL->EmitCall( OpCodes::Call, writeLine0objMI, nullptr );
      myFCIL->Emit( OpCodes::Ldloc_S, v0 );
      myFCIL->EmitCall( OpCodes::Call, getFilesMI, nullptr );
      myFCIL->Emit( OpCodes::Stloc_S, v3 );
      myFCIL->Emit( OpCodes::Br_S, evalForEachLabel );

      // foreach loop starts here.
      myFCIL->MarkLabel( topOfForEachLabel );

      // Load array of strings and index, store value at index for output.
      myFCIL->Emit( OpCodes::Ldloc_S, v3 );
      myFCIL->Emit( OpCodes::Ldloc_S, v1 );
      myFCIL->Emit( OpCodes::Ldelem_Ref );
      myFCIL->Emit( OpCodes::Stloc_S, v2 );
      myFCIL->Emit( OpCodes::Ldloc_S, v2 );
      myFCIL->EmitCall( OpCodes::Call, writeLine0objMI, nullptr );

      // Increment counter by one.
      myFCIL->Emit( OpCodes::Ldloc_S, v1 );
      myFCIL->Emit( OpCodes::Ldc_I4_1 );
      myFCIL->Emit( OpCodes::Add );
      myFCIL->Emit( OpCodes::Stloc_S, v1 );

      // Determine if end of file list array has been reached.
      myFCIL->MarkLabel( evalForEachLabel );
      myFCIL->Emit( OpCodes::Ldloc_S, v1 );
      myFCIL->Emit( OpCodes::Ldloc_S, v3 );
      myFCIL->Emit( OpCodes::Ldlen );
      myFCIL->Emit( OpCodes::Conv_I4 );
      myFCIL->Emit( OpCodes::Blt_S, topOfForEachLabel );

      //foreach loop end here.
      myFCIL->Emit( OpCodes::Ldstr, "---" );
      myFCIL->EmitCall( OpCodes::Call, writeLine0objMI, nullptr );
      myFCIL->Emit( OpCodes::Ldstr, "There are {0} files in {1}." );
      myFCIL->Emit( OpCodes::Ldloc_S, v1 );
      myFCIL->Emit( OpCodes::Box, int::typeid );
      myFCIL->Emit( OpCodes::Ldloc_S, v0 );
      myFCIL->EmitCall( OpCodes::Call, writeLine2objMI, nullptr );
      myFCIL->Emit( OpCodes::Ret );
      Type^ myType = myTypeBuilder->CreateType();
      myAsmBuilder->SetEntryPoint( myFCMethod );
      myAsmBuilder->Save( executableName );
      Console::WriteLine( "-- Method generated, type completed, and assembly saved to disk." );
      return myType;
   }
};

int main()
{
   String^ domainDir;
   String^ executableName = nullptr;
   Console::Write( "Enter a name for the file counting assembly: " );
   String^ executableNameNoExe = Console::ReadLine();
   executableName = String::Concat( executableNameNoExe, ".exe" );
   Console::WriteLine( "---" );
   domainDir = Environment::CurrentDirectory;
   AppDomain^ curDomain = Thread::GetDomain();

   // Create a new AppDomain, with the current directory as the base.
   Console::WriteLine( "Current Directory: {0}", Environment::CurrentDirectory );
   AppDomainSetup^ mySetupInfo = gcnew AppDomainSetup;
   mySetupInfo->ApplicationBase = domainDir;
   mySetupInfo->ApplicationName = executableNameNoExe;
   mySetupInfo->LoaderOptimization = LoaderOptimization::SingleDomain;
   AppDomain^ myDomain = AppDomain::CreateDomain( executableNameNoExe, nullptr, mySetupInfo );
   Console::WriteLine( "Creating a new AppDomain '{0}'...", executableNameNoExe );
   Console::WriteLine( "-- Base Directory = '{0}'", myDomain->BaseDirectory );
   Console::WriteLine( "-- Shadow Copy? = '{0}'", myDomain->ShadowCopyFiles );
   Console::WriteLine( "---" );
   Type^ myFCType = ADDyno::CreateADynamicAssembly(  &curDomain, executableNameNoExe );
   Console::WriteLine( "Loading '{0}' from '{1}'...", executableName, myDomain->BaseDirectory );
   BindingFlags bFlags = static_cast<BindingFlags>(BindingFlags::Public | BindingFlags::CreateInstance | BindingFlags::Instance);
   Object^ myObjInstance = myDomain->CreateInstanceAndUnwrap( executableNameNoExe, executableNameNoExe, false, bFlags, nullptr, nullptr, nullptr, nullptr, nullptr );
   Console::WriteLine( "Executing method 'CountLocalFiles' in {0}...", myObjInstance );
   array<Object^>^temp4 = nullptr;
   myFCType->InvokeMember( "CountLocalFiles", BindingFlags::InvokeMethod, nullptr, myObjInstance, temp4 );
}

using System;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Remoting;

class ADDyno

{

   public static Type CreateADynamicAssembly(ref AppDomain myNewDomain,
					     string executableNameNoExe)
   {

	string executableName = executableNameNoExe + ".exe";

	AssemblyName myAsmName = new AssemblyName();
	myAsmName.Name = executableNameNoExe;
	myAsmName.CodeBase = Environment.CurrentDirectory;

	AssemblyBuilder myAsmBuilder = myNewDomain.DefineDynamicAssembly(myAsmName,
						AssemblyBuilderAccess.RunAndSave);
	Console.WriteLine("-- Dynamic Assembly instantiated.");

	ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(executableNameNoExe,
								      executableName);

	TypeBuilder myTypeBuilder = myModBuilder.DefineType(executableNameNoExe,
						TypeAttributes.Public,
						typeof(MarshalByRefObject));

	MethodBuilder myFCMethod = myTypeBuilder.DefineMethod("CountLocalFiles",
						MethodAttributes.Public |
						MethodAttributes.Static,
						null,
						new Type[] {  });

	MethodInfo currentDirGetMI = typeof(Environment).GetProperty("CurrentDirectory").GetGetMethod();
	MethodInfo writeLine0objMI = typeof(Console).GetMethod("WriteLine",
				     new Type[] { typeof(string) });
	MethodInfo writeLine2objMI = typeof(Console).GetMethod("WriteLine",
				     new Type[] { typeof(string), typeof(object), typeof(object) });
	MethodInfo getFilesMI = typeof(Directory).GetMethod("GetFiles", 
				new Type[] { typeof(string) });

	myFCMethod.InitLocals = true;

	ILGenerator myFCIL = myFCMethod.GetILGenerator();

	Console.WriteLine("-- Generating MSIL method body...");
	LocalBuilder v0 = myFCIL.DeclareLocal(typeof(string));
	LocalBuilder v1 = myFCIL.DeclareLocal(typeof(int));
	LocalBuilder v2 = myFCIL.DeclareLocal(typeof(string));
	LocalBuilder v3 = myFCIL.DeclareLocal(typeof(string[]));

	Label evalForEachLabel = myFCIL.DefineLabel();
	Label topOfForEachLabel = myFCIL.DefineLabel();

	// Build the method body.

	myFCIL.EmitCall(OpCodes.Call, currentDirGetMI, null);
	myFCIL.Emit(OpCodes.Stloc_S, v0);
	myFCIL.Emit(OpCodes.Ldc_I4_0);
	myFCIL.Emit(OpCodes.Stloc_S, v1);
	myFCIL.Emit(OpCodes.Ldstr, "---");
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);
	myFCIL.Emit(OpCodes.Ldloc_S, v0);
	myFCIL.EmitCall(OpCodes.Call, getFilesMI, null);
	myFCIL.Emit(OpCodes.Stloc_S, v3);

	myFCIL.Emit(OpCodes.Br_S, evalForEachLabel);

	// foreach loop starts here.
	myFCIL.MarkLabel(topOfForEachLabel);
	
        // Load array of strings and index, store value at index for output.
	myFCIL.Emit(OpCodes.Ldloc_S, v3);
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Ldelem_Ref);
	myFCIL.Emit(OpCodes.Stloc_S, v2);

	myFCIL.Emit(OpCodes.Ldloc_S, v2);
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);

	// Increment counter by one.
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Ldc_I4_1);
	myFCIL.Emit(OpCodes.Add);
	myFCIL.Emit(OpCodes.Stloc_S, v1);

	// Determine if end of file list array has been reached.
	myFCIL.MarkLabel(evalForEachLabel);
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Ldloc_S, v3);
	myFCIL.Emit(OpCodes.Ldlen);
	myFCIL.Emit(OpCodes.Conv_I4);
	myFCIL.Emit(OpCodes.Blt_S, topOfForEachLabel);
	//foreach loop end here.

	myFCIL.Emit(OpCodes.Ldstr, "---");
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);
	myFCIL.Emit(OpCodes.Ldstr, "There are {0} files in {1}.");
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Box, typeof(int));
	myFCIL.Emit(OpCodes.Ldloc_S, v0);
	myFCIL.EmitCall(OpCodes.Call, writeLine2objMI, null);

	myFCIL.Emit(OpCodes.Ret);

	Type myType = myTypeBuilder.CreateType();

	myAsmBuilder.SetEntryPoint(myFCMethod);
	myAsmBuilder.Save(executableName);		
	Console.WriteLine("-- Method generated, type completed, and assembly saved to disk."); 

	return myType;

   }

   public static void Main() 
   {

	string domainDir, executableName = null;
	
	Console.Write("Enter a name for the file counting assembly: ");
	string executableNameNoExe = Console.ReadLine();
	executableName = executableNameNoExe + ".exe";
	Console.WriteLine("---");

	domainDir = Environment.CurrentDirectory;

	AppDomain curDomain = Thread.GetDomain();	


	// Create a new AppDomain, with the current directory as the base.

	Console.WriteLine("Current Directory: {0}", Environment.CurrentDirectory);
	AppDomainSetup mySetupInfo = new AppDomainSetup();
	mySetupInfo.ApplicationBase = domainDir;
	mySetupInfo.ApplicationName = executableNameNoExe;
	mySetupInfo.LoaderOptimization = LoaderOptimization.SingleDomain;

	AppDomain myDomain = AppDomain.CreateDomain(executableNameNoExe,
					null, mySetupInfo);

	Console.WriteLine("Creating a new AppDomain '{0}'...",
					executableNameNoExe);

	Console.WriteLine("-- Base Directory = '{0}'", myDomain.BaseDirectory); 
	Console.WriteLine("-- Shadow Copy? = '{0}'", myDomain.ShadowCopyFiles); 

	Console.WriteLine("---");
	Type myFCType = CreateADynamicAssembly(ref curDomain, 
					 executableNameNoExe);

	Console.WriteLine("Loading '{0}' from '{1}'...", executableName,
			  myDomain.BaseDirectory.ToString());


	BindingFlags bFlags = (BindingFlags.Public | BindingFlags.CreateInstance |
			       BindingFlags.Instance);

	Object myObjInstance = myDomain.CreateInstanceAndUnwrap(executableNameNoExe,
				executableNameNoExe, false, bFlags, 
				null, null, null, null, null);

	Console.WriteLine("Executing method 'CountLocalFiles' in {0}...",
			   myObjInstance.ToString());

	myFCType.InvokeMember("CountLocalFiles", BindingFlags.InvokeMethod, null,
				myObjInstance, new object[] { });
			
		
   }

}

Imports System
Imports System.IO
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.Remoting



Class ADDyno
   
   
   
   Public Shared Function CreateADynamicAssembly(ByRef myNewDomain As AppDomain, executableNameNoExe As String) As Type
      
      Dim executableName As String = executableNameNoExe + ".exe"
      
      Dim myAsmName As New AssemblyName()
      myAsmName.Name = executableNameNoExe
      myAsmName.CodeBase = Environment.CurrentDirectory
      
      Dim myAsmBuilder As AssemblyBuilder = myNewDomain.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.RunAndSave)
      Console.WriteLine("-- Dynamic Assembly instantiated.")
      
      Dim myModBuilder As ModuleBuilder = myAsmBuilder.DefineDynamicModule(executableNameNoExe, executableName)
      
      Dim myTypeBuilder As TypeBuilder = myModBuilder.DefineType(executableNameNoExe, TypeAttributes.Public, GetType(MarshalByRefObject))
      
      Dim myFCMethod As MethodBuilder = myTypeBuilder.DefineMethod("CountLocalFiles", MethodAttributes.Public Or MethodAttributes.Static, Nothing, New Type() {})
      
      Dim currentDirGetMI As MethodInfo = GetType(Environment).GetProperty("CurrentDirectory").GetGetMethod()
      Dim writeLine0objMI As MethodInfo = GetType(Console).GetMethod("WriteLine", New Type() {GetType(String)})
      Dim writeLine2objMI As MethodInfo = GetType(Console).GetMethod("WriteLine", New Type() {GetType(String), GetType(Object), GetType(Object)})
      Dim getFilesMI As MethodInfo = GetType(Directory).GetMethod("GetFiles", New Type() {GetType(String)})
      
      myFCMethod.InitLocals = True
      
      Dim myFCIL As ILGenerator = myFCMethod.GetILGenerator()
      
      Console.WriteLine("-- Generating MSIL method body...")
      Dim v0 As LocalBuilder = myFCIL.DeclareLocal(GetType(String))
      Dim v1 As LocalBuilder = myFCIL.DeclareLocal(GetType(Integer))
      Dim v2 As LocalBuilder = myFCIL.DeclareLocal(GetType(String))
      Dim v3 As LocalBuilder = myFCIL.DeclareLocal(GetType(String()))
      
      Dim evalForEachLabel As Label = myFCIL.DefineLabel()
      Dim topOfForEachLabel As Label = myFCIL.DefineLabel()
      
      ' Build the method body.
      myFCIL.EmitCall(OpCodes.Call, currentDirGetMI, Nothing)
      myFCIL.Emit(OpCodes.Stloc_S, v0)
      myFCIL.Emit(OpCodes.Ldc_I4_0)
      myFCIL.Emit(OpCodes.Stloc_S, v1)
      myFCIL.Emit(OpCodes.Ldstr, "---")
      myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, Nothing)
      myFCIL.Emit(OpCodes.Ldloc_S, v0)
      myFCIL.EmitCall(OpCodes.Call, getFilesMI, Nothing)
      myFCIL.Emit(OpCodes.Stloc_S, v3)
      
      myFCIL.Emit(OpCodes.Br_S, evalForEachLabel)
      
      ' foreach loop starts here.
      myFCIL.MarkLabel(topOfForEachLabel)
      
      ' Load array of strings and index, store value at index for output.
      myFCIL.Emit(OpCodes.Ldloc_S, v3)
      myFCIL.Emit(OpCodes.Ldloc_S, v1)
      myFCIL.Emit(OpCodes.Ldelem_Ref)
      myFCIL.Emit(OpCodes.Stloc_S, v2)
      
      myFCIL.Emit(OpCodes.Ldloc_S, v2)
      myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, Nothing)
      
      ' Increment counter by one.
      myFCIL.Emit(OpCodes.Ldloc_S, v1)
      myFCIL.Emit(OpCodes.Ldc_I4_1)
      myFCIL.Emit(OpCodes.Add)
      myFCIL.Emit(OpCodes.Stloc_S, v1)
      
      ' Determine if end of file list array has been reached.
      myFCIL.MarkLabel(evalForEachLabel)
      myFCIL.Emit(OpCodes.Ldloc_S, v1)
      myFCIL.Emit(OpCodes.Ldloc_S, v3)
      myFCIL.Emit(OpCodes.Ldlen)
      myFCIL.Emit(OpCodes.Conv_I4)
      myFCIL.Emit(OpCodes.Blt_S, topOfForEachLabel)
      'foreach loop end here.
      myFCIL.Emit(OpCodes.Ldstr, "---")
      myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, Nothing)
      myFCIL.Emit(OpCodes.Ldstr, "There are {0} files in {1}.")
      myFCIL.Emit(OpCodes.Ldloc_S, v1)
      myFCIL.Emit(OpCodes.Box, GetType(Integer))
      myFCIL.Emit(OpCodes.Ldloc_S, v0)
      myFCIL.EmitCall(OpCodes.Call, writeLine2objMI, Nothing)
      
      myFCIL.Emit(OpCodes.Ret)
      
      Dim myType As Type = myTypeBuilder.CreateType()
      
      myAsmBuilder.SetEntryPoint(myFCMethod)
      myAsmBuilder.Save(executableName)
      Console.WriteLine("-- Method generated, type completed, and assembly saved to disk.")
      
      Return myType
   End Function 'CreateADynamicAssembly
    
   
   Public Shared Sub Main()
      
      Dim executableName As String = Nothing
      Dim domainDir As String
      
      Console.Write("Enter a name for the file counting assembly: ")
      Dim executableNameNoExe As String = Console.ReadLine()
      executableName = executableNameNoExe + ".exe"
      Console.WriteLine("---")
      
      domainDir = Environment.CurrentDirectory
      
      Dim curDomain As AppDomain = Thread.GetDomain()
      
      
      ' Create a new AppDomain, with the current directory as the base.
      Console.WriteLine("Current Directory: {0}", Environment.CurrentDirectory)
      Dim mySetupInfo As New AppDomainSetup()
      mySetupInfo.ApplicationBase = domainDir
      mySetupInfo.ApplicationName = executableNameNoExe
      mySetupInfo.LoaderOptimization = LoaderOptimization.SingleDomain
      
      Dim myDomain As AppDomain = AppDomain.CreateDomain(executableNameNoExe, Nothing, mySetupInfo)
      
      Console.WriteLine("Creating a new AppDomain '{0}'...", executableNameNoExe)
      
      Console.WriteLine("-- Base Directory = '{0}'", myDomain.BaseDirectory)
      Console.WriteLine("-- Shadow Copy? = '{0}'", myDomain.ShadowCopyFiles)
      
      Console.WriteLine("---")
      Dim myFCType As Type = CreateADynamicAssembly(curDomain, executableNameNoExe)
      
      Console.WriteLine("Loading '{0}' from '{1}'...", executableName, myDomain.BaseDirectory.ToString())
      
      
      Dim bFlags As BindingFlags = BindingFlags.Public Or BindingFlags.CreateInstance Or BindingFlags.Instance
      
      Dim myObjInstance As [Object] = myDomain.CreateInstanceAndUnwrap(executableNameNoExe, executableNameNoExe, False, bFlags, Nothing, Nothing, Nothing, Nothing, Nothing)
      
      Console.WriteLine("Executing method 'CountLocalFiles' in {0}...", myObjInstance.ToString())
      
      myFCType.InvokeMember("CountLocalFiles", BindingFlags.InvokeMethod, Nothing, myObjInstance, New Object() {})
   End Sub 'Main
End Class 'ADDyno 



Comentarios

Se trata de un método de conveniencia que combina CreateInstance y ObjectHandle.Unwrap.This is a convenience method that combines CreateInstance and ObjectHandle.Unwrap. Este método llama al constructor predeterminado para typeName.This method calls the default constructor for typeName.

Consulte AssemblyName de formato de assemblyName.See AssemblyName for the format of assemblyName. Consulte la Type.FullName propiedad de formato de typeName.See the Type.FullName property for the format of typeName.

Nota

Si realiza una llamada enlazada a un método M de un objeto de tipo T1 que devolvió CreateInstanceAndUnwrap, y que el método realiza una llamada enlazada a un método de un objeto de tipo T2 en un ensamblado C distinto el ensamblado actual o el ensamblado que contiene T1, ensamblado C se carga en el dominio de aplicación actual.If you make an early-bound call to a method M of an object of type T1 that was returned by CreateInstanceAndUnwrap, and that method makes an early-bound call to a method of an object of type T2 in an assembly C other than the current assembly or the assembly containing T1, assembly C is loaded into the current application domain. Esta carga se produce incluso si el enlace anticipado llamada a T1.M() se realizó en el cuerpo de un DynamicMethod, o en otro código generado dinámicamente.This loading occurs even if the early-bound call to T1.M() was made in the body of a DynamicMethod, or in other dynamically generated code. Si el dominio actual es el dominio predeterminado, el ensamblado C no se puede descargar hasta que finaliza el proceso.If the current domain is the default domain, assembly C cannot be unloaded until the process ends. Si más adelante, el dominio actual intenta cargar el ensamblado C, podría producir un error en la carga.If the current domain later attempts to load assembly C, the load might fail.

Seguridad

FileIOPermissionAccess
para que poder leer el archivo que contiene el manifiesto del ensamblado.for the ability to read the file containing the assembly manifest. Enumeración asociada: ReadAssociated enumeration: Read

WebPermission
Para poder acceder a la ubicación del ensamblado si el ensamblado no es local.for the ability to access the location of the assembly if the assembly is not local.

SecurityPermission
Para poder llamar a código no administrado al crear una instancia de un delegado.for the ability to call unmanaged code when creating an instance of a delegate. Enumeración asociada: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
la capacidad invocar operaciones en todos los miembros de tipo.for the ability to invoke operations on all type members. Enumeración asociada: MemberAccessAssociated enumeration: MemberAccess

Consulte también:

CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Crea una nueva instancia del tipo especificado definido en el ensamblado indicado, especificando si se pasa por alto el modelo de mayúsculas y minúsculas del nombre de tipo, los atributos de enlace y el enlazador que se usan para seleccionar el tipo que se va a crear, los argumentos del constructor, la referencia cultural y los atributos de activación.Creates a new instance of the specified type defined in the specified assembly, specifying whether the case of the type name is ignored; the binding attributes and the binder that are used to select the type to be created; the arguments of the constructor; the culture; and the activation attributes.

public:
 System::Object ^ CreateInstanceAndUnwrap(System::String ^ assemblyName, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes);
public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
member this.CreateInstanceAndUnwrap : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> obj

Parámetros

assemblyName
String String String String

Nombre para mostrar del ensamblado.The display name of the assembly. Vea FullName.See FullName.

typeName
String String String String

Nombre completo del tipo solicitado, incluido el espacio de nombres, pero no el ensamblado, tal y como lo devuelve la propiedad FullName.The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

ignoreCase
Boolean Boolean Boolean Boolean

Valor booleano que especifica si va a realizarse una búsqueda con distinción de mayúsculas y minúsculas.A Boolean value specifying whether to perform a case-sensitive search or not.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

Combinación de cero o más marcadores de bits que afectan a la búsqueda del constructor de typeName.A combination of zero or more bit flags that affect the search for the typeName constructor. Si bindingAttr es cero, se realiza una búsqueda de constructores públicos que distingue mayúsculas de minúsculas.If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder Binder Binder Binder

Objeto que permite el enlace, la conversión de tipos de argumentos, la invocación de miembros y la recuperación de objetos MemberInfo mediante la reflexión.An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects using reflection. Si binder es null, se usará el enlazador predeterminado.If binder is null, the default binder is used.

args
Object[]

Argumentos que se van a pasar al constructor.The arguments to pass to the constructor. Esta matriz de argumentos debe coincidir en número, orden y tipo con los parámetros del constructor que se va a invocar.This array of arguments must match in number, order, and type the parameters of the constructor to invoke. Si se prefiere usar el constructor predeterminado, args debe ser una matriz vacía o null.If the default constructor is preferred, args must be an empty array or null.

culture
CultureInfo CultureInfo CultureInfo CultureInfo

Objeto específico de la referencia cultural que se usa para regir la conversión de tipos.A culture-specific object used to govern the coercion of types. Si culture es null, se usa CultureInfo del subproceso actual.If culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

Matriz de uno o más atributos que puede participar en la activación.An array of one or more attributes that can participate in activation. Normalmente, una matriz que contiene un solo objeto UrlAttribute.Typically, an array that contains a single UrlAttribute object. que especifica la dirección URL necesaria para activar un objeto remoto.that specifies the URL that is required to activate a remote object.

Este parámetro está relacionado con los objetos activados por el cliente.This parameter is related to client-activated objects. La activación por parte del cliente es una tecnología heredada que se conserva por compatibilidad con versiones anteriores, pero no se recomienda para nuevo desarrollo.Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Las aplicaciones distribuidas deberían usar Windows Communication Foundation.Distributed applications should instead use Windows Communication Foundation.

Devoluciones

Instancia del objeto especificado por typeName.An instance of the object specified by typeName.

Excepciones

assemblyName o typeName es null.assemblyName or typeName is null.

No se encontró ningún constructor coincidente.No matching constructor was found.

No se encontró typename en assemblyName.typename was not found in assemblyName.

No se encontró assemblyName.assemblyName was not found.

El llamador no tiene permiso para llamar a este constructor.The caller does not have permission to call this constructor.

El llamador no puede ofrecer atributos de activación para un objeto que no hereda de MarshalByRefObject.The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

assemblyName no es un ensamblado válido.assemblyName is not a valid assembly.

-o bien--or- assemblyName se compiló con una versión de Common Language Runtime posterior a la versión que está cargada actualmente.assemblyName was compiled with a later version of the common language runtime than the version that is currently loaded.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Ejemplos

El ejemplo siguiente muestra el uso de la ignoreCase parámetro.The following sample demonstrates the use of the ignoreCase parameter.

using namespace System;
using namespace System::Reflection;
static void InstantiateINT32( bool ignoreCase )
{
   try
   {
      AppDomain^ currentDomain = AppDomain::CurrentDomain;
      Object^ instance = currentDomain->CreateInstanceAndUnwrap( 
         "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 
         "SYSTEM.INT32", 
         ignoreCase, 
         BindingFlags::Default, 
         nullptr, 
         nullptr, 
         nullptr, 
         nullptr, 
         nullptr );
      Console::WriteLine( instance->GetType() );
   }
   catch ( TypeLoadException^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}

int main()
{
   InstantiateINT32( false ); // Failed!
   InstantiateINT32( true ); // OK!
}

using System;
using System.Reflection;

class Test {

   static void Main() {
      InstantiateINT32(false);     // Failed!
      InstantiateINT32(true);      // OK!
   }
   
   static void InstantiateINT32(bool ignoreCase) {
      try {
         AppDomain currentDomain = AppDomain.CurrentDomain;
         object instance = currentDomain.CreateInstanceAndUnwrap(
            "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
            "SYSTEM.INT32",
            ignoreCase,
            BindingFlags.Default,
            null,
            null,
            null,
            null,
            null
         );
         Console.WriteLine(instance.GetType());
      } catch (TypeLoadException e) {
         Console.WriteLine(e.Message);
      }
   }
}
Imports System
Imports System.Reflection

Module Test

   Sub Main()
      InstantiateINT32(False)	' Failed!
      InstantiateINT32(True)	' OK!
   End Sub 'Main

   Sub InstantiateINT32(ignoreCase As Boolean)
      Try
         Dim currentDomain As AppDomain = AppDomain.CurrentDomain
         Dim instance As Object = currentDomain.CreateInstanceAndUnwrap( _
            "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", _
            "SYSTEM.INT32", _
            ignoreCase, _
            BindingFlags.Default, _
            Nothing, _
            Nothing, _
            Nothing, _
            Nothing, _
            Nothing  _
         )
         Console.WriteLine(instance.GetType())
      Catch e As TypeLoadException
         Console.WriteLine(e.Message)
      End Try
   End Sub 'InstantiateINT32

End Module 'Test

Comentarios

Se trata de un método de conveniencia que combina CreateInstance y ObjectHandle.Unwrap.This is a convenience method that combines CreateInstance and ObjectHandle.Unwrap.

Consulte AssemblyName de formato de assemblyName.See AssemblyName for the format of assemblyName. Consulte la Type.FullName propiedad de formato de typeName.See the Type.FullName property for the format of typeName.

Nota

Si realiza una llamada enlazada a un método M de un objeto de tipo T1 que devolvió CreateInstanceAndUnwrap, y que el método realiza una llamada enlazada a un método de un objeto de tipo T2 en un ensamblado C distinto el ensamblado actual o el ensamblado que contiene T1, ensamblado C se carga en el dominio de aplicación actual.If you make an early-bound call to a method M of an object of type T1 that was returned by CreateInstanceAndUnwrap, and that method makes an early-bound call to a method of an object of type T2 in an assembly C other than the current assembly or the assembly containing T1, assembly C is loaded into the current application domain. Esta carga se produce incluso si el enlace anticipado llamada a T1.M() se realizó en el cuerpo de un DynamicMethod, o en otro código generado dinámicamente.This loading occurs even if the early-bound call to T1.M() was made in the body of a DynamicMethod, or in other dynamically generated code. Si el dominio actual es el dominio predeterminado, el ensamblado C no se puede descargar hasta que finaliza el proceso.If the current domain is the default domain, assembly C cannot be unloaded until the process ends. Si más adelante, el dominio actual intenta cargar el ensamblado C, podría producir un error en la carga.If the current domain later attempts to load assembly C, the load might fail.

Seguridad

FileIOPermissionAccess
para que poder leer el archivo que contiene el manifiesto del ensamblado.for the ability to read the file containing the assembly manifest. Enumeración asociada: ReadAssociated enumeration: Read

WebPermission
Para poder acceder a la ubicación del ensamblado si el ensamblado no es local.for the ability to access the location of the assembly if the assembly is not local.

SecurityPermission
Para poder llamar a código no administrado al crear una instancia de un delegado.for the ability to call unmanaged code when creating an instance of a delegate. Enumeración asociada: UnmanagedCodeAssociated enumeration: UnmanagedCode

ReflectionPermission
la capacidad invocar operaciones en todos los miembros de tipo.for the ability to invoke operations on all type members. Enumeración asociada: MemberAccessAssociated enumeration: MemberAccess

Consulte también:

CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

Advertencia

Esta API está ya obsoleta.

Crea una nueva instancia del tipo especificado.Creates a new instance of the specified type. Los parámetros especifican el nombre del tipo, así como la forma en que se encontró y se creó.Parameters specify the name of the type, and how it is found and created.

public:
 System::Object ^ CreateInstanceAndUnwrap(System::String ^ assemblyName, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes, System::Security::Policy::Evidence ^ securityAttributes);
[System.Obsolete("Use an overload that does not take an Evidence parameter")]
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceAndUnwrap which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityAttributes);
member this.CreateInstanceAndUnwrap : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> obj

Parámetros

assemblyName
String String String String

Nombre para mostrar del ensamblado.The display name of the assembly. Vea FullName.See FullName.

typeName
String String String String

Nombre completo del tipo solicitado, incluido el espacio de nombres, pero no el ensamblado, tal y como lo devuelve la propiedad FullName.The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

ignoreCase
Boolean Boolean Boolean Boolean

Valor booleano que especifica si va a realizarse una búsqueda con distinción de mayúsculas y minúsculas.A Boolean value specifying whether to perform a case-sensitive search or not.

bindingAttr
BindingFlags BindingFlags BindingFlags BindingFlags

Combinación de cero o más marcadores de bits que afectan a la búsqueda del constructor de typeName.A combination of zero or more bit flags that affect the search for the typeName constructor. Si bindingAttr es cero, se realiza una búsqueda de constructores públicos que distingue mayúsculas de minúsculas.If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder Binder Binder Binder

Objeto que permite el enlace, la conversión de tipos de argumentos, la invocación de miembros y la recuperación de objetos MemberInfo mediante la reflexión.An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects using reflection. Si binder es null, se usará el enlazador predeterminado.If binder is null, the default binder is used.

args
Object[]

Argumentos que se van a pasar al constructor.The arguments to pass to the constructor. Esta matriz de argumentos debe coincidir en número, orden y tipo con los parámetros del constructor que se va a invocar.This array of arguments must match in number, order, and type the parameters of the constructor to invoke. Si se prefiere usar el constructor predeterminado, args debe ser una matriz vacía o null.If the default constructor is preferred, args must be an empty array or null.

culture
CultureInfo CultureInfo CultureInfo CultureInfo

Objeto específico de la referencia cultural que se usa para regir la conversión de tipos.A culture-specific object used to govern the coercion of types. Si culture es null, se usa CultureInfo del subproceso actual.If culture is null, the CultureInfo for the current thread is used.

activationAttributes
Object[]

Matriz de uno o más atributos que puede participar en la activación.An array of one or more attributes that can participate in activation. Normalmente, una matriz que contiene un único objeto UrlAttribute que especifica la dirección URL necesaria para activar un objeto remoto.Typically, an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

Este parámetro está relacionado con los objetos activados por el cliente.This parameter is related to client-activated objects. La activación por parte del cliente es una tecnología heredada que se conserva por compatibilidad con versiones anteriores, pero no se recomienda para nuevo desarrollo.Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Las aplicaciones distribuidas deberían usar Windows Communication Foundation.Distributed applications should instead use Windows Communication Foundation.

securityAttributes
Evidence Evidence Evidence Evidence

Información que se usa para autorizar la creación de typeName.Information used to authorize creation of typeName.

Devoluciones

Instancia del objeto especificado por typeName.An instance of the object specified by typeName.

Excepciones

assemblyName o typeName es null.assemblyName or typeName is null.

No se encontró ningún constructor coincidente.No matching constructor was found.

No se encontró typename en assemblyName.typename was not found in assemblyName.

No se encontró assemblyName.assemblyName was not found.

El llamador no tiene permiso para llamar a este constructor.The caller does not have permission to call this constructor.

El llamador no puede ofrecer atributos de activación para un objeto que no hereda de MarshalByRefObject.The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

La operación se intenta en un dominio de aplicación descargado.The operation is attempted on an unloaded application domain.

assemblyName no es un ensamblado válido.assemblyName is not a valid assembly.

-o bien--or- La versión 2.0 u otra posterior del Common Language Runtime está cargada actualmente y assemblyName se compiló con una versión posterior.Version 2.0 or later of the common language runtime is currently loaded and assemblyName was compiled with a later version.

Se cargó un ensamblado o módulo dos veces con dos evidencias diferentes.An assembly or module was loaded twice with two different evidences.

Ejemplos

El ejemplo siguiente muestra el uso de la ignoreCase parámetro.The following sample demonstrates the use of the ignoreCase parameter.

using namespace System;
using namespace System::Reflection;
static void InstantiateINT32( bool ignoreCase )
{
   try
   {
      AppDomain^ currentDomain = AppDomain::CurrentDomain;
      Object^ instance = currentDomain->CreateInstanceAndUnwrap( 
         "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", 
         "SYSTEM.INT32", 
         ignoreCase, 
         BindingFlags::Default, 
         nullptr, 
         nullptr, 
         nullptr, 
         nullptr, 
         nullptr );
      Console::WriteLine( instance->GetType() );
   }
   catch ( TypeLoadException^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}

int main()
{
   InstantiateINT32( false ); // Failed!
   InstantiateINT32( true ); // OK!
}

using System;
using System.Reflection;

class Test {

   static void Main() {
      InstantiateINT32(false);     // Failed!
      InstantiateINT32(true);      // OK!
   }
   
   static void InstantiateINT32(bool ignoreCase) {
      try {
         AppDomain currentDomain = AppDomain.CurrentDomain;
         object instance = currentDomain.CreateInstanceAndUnwrap(
            "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
            "SYSTEM.INT32",
            ignoreCase,
            BindingFlags.Default,
            null,
            null,
            null,
            null,
            null
         );
         Console.WriteLine(instance.GetType());
      } catch (TypeLoadException e) {
         Console.WriteLine(e.Message);
      }
   }
}
Imports System
Imports System.Reflection

Module Test

   Sub Main()
      InstantiateINT32(False)	' Failed!
      InstantiateINT32(True)	' OK!
   End Sub 'Main

   Sub InstantiateINT32(ignoreCase As Boolean)
      Try
         Dim currentDomain As AppDomain = AppDomain.CurrentDomain
         Dim instance As Object = currentDomain.CreateInstanceAndUnwrap( _
            "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", _
            "SYSTEM.INT32", _
            ignoreCase, _
            BindingFlags.Default, _
            Nothing, _
            Nothing, _
            Nothing, _
            Nothing, _
            Nothing  _
         )
         Console.WriteLine(instance.GetType())
      Catch e As TypeLoadException
         Console.WriteLine(e.Message)
      End Try
   End Sub 'InstantiateINT32

End Module 'Test

Comentarios

Se trata de un método de conveniencia que combina CreateInstance y ObjectHandle.Unwrap.This is a convenience method that combines CreateInstance and ObjectHandle.Unwrap.

Consulte AssemblyName de formato de assemblyName.See AssemblyName for the format of assemblyName. Consulte la Type.FullName propiedad de formato de typeName.See the Type.FullName property for the format of typeName.

Nota

Si realiza una llamada enlazada a un método M de un objeto de tipo T1 que devolvió CreateInstanceAndUnwrap, y que el método realiza una llamada enlazada a un método de un objeto de tipo T2 en un ensamblado C distinto el ensamblado actual o el ensamblado que contiene T1, ensamblado C se carga en el dominio de aplicación actual.If you make an early-bound call to a method M of an object of type T1 that was returned by CreateInstanceAndUnwrap, and that method makes an early-bound call to a method of an object of type T2 in an assembly C other than the current assembly or the assembly containing T1, assembly C is loaded into the current application domain. Esta carga se produce incluso si el enlace anticipado llamada a T1.M() se realizó en el cuerpo de un DynamicMethod, o en otro código generado dinámicamente.This loading occurs even if the early-bound call to T1.M() was made in the body of a DynamicMethod, or in other dynamically generated code. Si el dominio actual es el dominio predeterminado, el ensamblado C no se puede descargar hasta que finaliza el proceso.If the current domain is the default domain, assembly C cannot be unloaded until the process ends. Si más adelante, el dominio actual intenta cargar el ensamblado C, podría producir un error en la carga.If the current domain later attempts to load assembly C, the load might fail.

Seguridad

FileIOPermissionAccess
para que poder leer el archivo que contiene el manifiesto del ensamblado.for the ability to read the file containing the assembly manifest. Enumeración asociada: ReadAssociated enumeration: Read

WebPermission
Para poder acceder a la ubicación del ensamblado si el ensamblado no es local.for the ability to access the location of the assembly if the assembly is not local.

SecurityPermission
para cargar un ensamblado con la evidencia.to load an assembly with evidence. Enumeración asociada: ControlEvidence.Associated enumeration: ControlEvidence.

ReflectionPermission
la capacidad invocar operaciones en todos los miembros de tipo.for the ability to invoke operations on all type members. Enumeración asociada: MemberAccessAssociated enumeration: MemberAccess

Consulte también:

Se aplica a