AssemblyBuilder Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Define e representa um assembly dinâmico.
public ref class AssemblyBuilder sealed : System::Reflection::Assembly
public ref class AssemblyBuilder abstract : System::Reflection::Assembly
public ref class AssemblyBuilder sealed : System::Reflection::Assembly, System::Runtime::InteropServices::_AssemblyBuilder
public sealed class AssemblyBuilder : System.Reflection.Assembly
public abstract class AssemblyBuilder : System.Reflection.Assembly
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
public sealed class AssemblyBuilder : System.Reflection.Assembly, System.Runtime.InteropServices._AssemblyBuilder
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AssemblyBuilder : System.Reflection.Assembly, System.Runtime.InteropServices._AssemblyBuilder
type AssemblyBuilder = class
inherit Assembly
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
type AssemblyBuilder = class
inherit Assembly
interface _AssemblyBuilder
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type AssemblyBuilder = class
inherit Assembly
interface _AssemblyBuilder
Public NotInheritable Class AssemblyBuilder
Inherits Assembly
Public MustInherit Class AssemblyBuilder
Inherits Assembly
Public NotInheritable Class AssemblyBuilder
Inherits Assembly
Implements _AssemblyBuilder
- Herança
- Derivado
- Atributos
- Implementações
Exemplos
O exemplo de código a seguir mostra como definir e usar um assembly dinâmico. O assembly de exemplo contém um tipo, MyDynamicType
, que tem um campo privado, uma propriedade que obtém e define o campo privado, construtores que inicializam o campo privado e um método que multiplica um número fornecido pelo usuário pelo valor do campo privado e retorna o resultado.
using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
void main()
{
// This code creates an assembly that contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In Visual C++ the type might look like this:
/*
public ref class MyDynamicType
{
private:
int m_number;
public:
MyDynamicType() : m_number(42) {};
MyDynamicType(int initNumber) : m_number(initNumber) {};
property int Number
{
int get() { return m_number; }
void set(int value) { m_number = value; }
}
int MyMethod(int multiplier)
{
return m_number * multiplier;
}
};
*/
AssemblyName^ aName = gcnew AssemblyName("DynamicAssemblyExample");
AssemblyBuilder^ ab =
AssemblyBuilder::DefineDynamicAssembly(
aName,
AssemblyBuilderAccess::Run);
// The module name is usually the same as the assembly name
ModuleBuilder^ mb =
ab->DefineDynamicModule(aName->Name);
TypeBuilder^ tb = mb->DefineType(
"MyDynamicType",
TypeAttributes::Public);
// Add a private field of type int (Int32).
FieldBuilder^ fbNumber = tb->DefineField(
"m_number",
int::typeid,
FieldAttributes::Private);
// Define a constructor that takes an integer argument and
// stores it in the private field.
array<Type^>^ parameterTypes = { int::typeid };
ConstructorBuilder^ ctor1 = tb->DefineConstructor(
MethodAttributes::Public,
CallingConventions::Standard,
parameterTypes);
ILGenerator^ ctor1IL = ctor1->GetILGenerator();
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before calling the base
// class constructor. Specify the default constructor of the
// base class (System::Object) by passing an empty array of
// types (Type::EmptyTypes) to GetConstructor.
ctor1IL->Emit(OpCodes::Ldarg_0);
ctor1IL->Emit(OpCodes::Call,
Object::typeid->GetConstructor(Type::EmptyTypes));
// Push the instance on the stack before pushing the argument
// that is to be assigned to the private field m_number.
ctor1IL->Emit(OpCodes::Ldarg_0);
ctor1IL->Emit(OpCodes::Ldarg_1);
ctor1IL->Emit(OpCodes::Stfld, fbNumber);
ctor1IL->Emit(OpCodes::Ret);
// Define a default constructor that supplies a default value
// for the private field. For parameter types, pass the empty
// array of types or pass nullptr.
ConstructorBuilder^ ctor0 = tb->DefineConstructor(
MethodAttributes::Public,
CallingConventions::Standard,
Type::EmptyTypes);
ILGenerator^ ctor0IL = ctor0->GetILGenerator();
ctor0IL->Emit(OpCodes::Ldarg_0);
ctor0IL->Emit(OpCodes::Call,
Object::typeid->GetConstructor(Type::EmptyTypes));
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before pushing the default
// value on the stack.
ctor0IL->Emit(OpCodes::Ldarg_0);
ctor0IL->Emit(OpCodes::Ldc_I4_S, 42);
ctor0IL->Emit(OpCodes::Stfld, fbNumber);
ctor0IL->Emit(OpCodes::Ret);
// Define a property named Number that gets and sets the private
// field.
//
// The last argument of DefineProperty is nullptr, because the
// property has no parameters. (If you don't specify nullptr, you must
// specify an array of Type objects. For a parameterless property,
// use the built-in array with no elements: Type::EmptyTypes)
PropertyBuilder^ pbNumber = tb->DefineProperty(
"Number",
PropertyAttributes::HasDefault,
int::typeid,
nullptr);
// The property "set" and property "get" methods require a special
// set of attributes.
MethodAttributes getSetAttr = MethodAttributes::Public |
MethodAttributes::SpecialName | MethodAttributes::HideBySig;
// Define the "get" accessor method for Number. The method returns
// an integer and has no arguments. (Note that nullptr could be
// used instead of Types::EmptyTypes)
MethodBuilder^ mbNumberGetAccessor = tb->DefineMethod(
"get_Number",
getSetAttr,
int::typeid,
Type::EmptyTypes);
ILGenerator^ numberGetIL = mbNumberGetAccessor->GetILGenerator();
// For an instance property, argument zero is the instance. Load the
// instance, then load the private field and return, leaving the
// field value on the stack.
numberGetIL->Emit(OpCodes::Ldarg_0);
numberGetIL->Emit(OpCodes::Ldfld, fbNumber);
numberGetIL->Emit(OpCodes::Ret);
// Define the "set" accessor method for Number, which has no return
// type and takes one argument of type int (Int32).
MethodBuilder^ mbNumberSetAccessor = tb->DefineMethod(
"set_Number",
getSetAttr,
nullptr,
gcnew array<Type^> { int::typeid });
ILGenerator^ numberSetIL = mbNumberSetAccessor->GetILGenerator();
// Load the instance and then the numeric argument, then store the
// argument in the field.
numberSetIL->Emit(OpCodes::Ldarg_0);
numberSetIL->Emit(OpCodes::Ldarg_1);
numberSetIL->Emit(OpCodes::Stfld, fbNumber);
numberSetIL->Emit(OpCodes::Ret);
// Last, map the "get" and "set" accessor methods to the
// PropertyBuilder. The property is now complete.
pbNumber->SetGetMethod(mbNumberGetAccessor);
pbNumber->SetSetMethod(mbNumberSetAccessor);
// Define a method that accepts an integer argument and returns
// the product of that integer and the private field m_number. This
// time, the array of parameter types is created on the fly.
MethodBuilder^ meth = tb->DefineMethod(
"MyMethod",
MethodAttributes::Public,
int::typeid,
gcnew array<Type^> { int::typeid });
ILGenerator^ methIL = meth->GetILGenerator();
// To retrieve the private instance field, load the instance it
// belongs to (argument zero). After loading the field, load the
// argument one and then multiply. Return from the method with
// the return value (the product of the two numbers) on the
// execution stack.
methIL->Emit(OpCodes::Ldarg_0);
methIL->Emit(OpCodes::Ldfld, fbNumber);
methIL->Emit(OpCodes::Ldarg_1);
methIL->Emit(OpCodes::Mul);
methIL->Emit(OpCodes::Ret);
// Finish the type->
Type^ t = tb->CreateType();
// Because AssemblyBuilderAccess includes Run, the code can be
// executed immediately. Start by getting reflection objects for
// the method and the property.
MethodInfo^ mi = t->GetMethod("MyMethod");
PropertyInfo^ pi = t->GetProperty("Number");
// Create an instance of MyDynamicType using the default
// constructor.
Object^ o1 = Activator::CreateInstance(t);
// Display the value of the property, then change it to 127 and
// display it again. Use nullptr to indicate that the property
// has no index.
Console::WriteLine("o1->Number: {0}", pi->GetValue(o1, nullptr));
pi->SetValue(o1, 127, nullptr);
Console::WriteLine("o1->Number: {0}", pi->GetValue(o1, nullptr));
// Call MyMethod, passing 22, and display the return value, 22
// times 127. Arguments must be passed as an array, even when
// there is only one.
array<Object^>^ arguments = { 22 };
Console::WriteLine("o1->MyMethod(22): {0}",
mi->Invoke(o1, arguments));
// Create an instance of MyDynamicType using the constructor
// that specifies m_Number. The constructor is identified by
// matching the types in the argument array. In this case,
// the argument array is created on the fly. Display the
// property value.
Object^ o2 = Activator::CreateInstance(t,
gcnew array<Object^> { 5280 });
Console::WriteLine("o2->Number: {0}", pi->GetValue(o2, nullptr));
};
/* This code produces the following output:
o1->Number: 42
o1->Number: 127
o1->MyMethod(22): 2794
o2->Number: 5280
*/
using System;
using System.Reflection;
using System.Reflection.Emit;
class DemoAssemblyBuilder
{
public static void Main()
{
// This code creates an assembly that contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In C# the type might look like this:
/*
public class MyDynamicType
{
private int m_number;
public MyDynamicType() : this(42) {}
public MyDynamicType(int initNumber)
{
m_number = initNumber;
}
public int Number
{
get { return m_number; }
set { m_number = value; }
}
public int MyMethod(int multiplier)
{
return m_number * multiplier;
}
}
*/
var aName = new AssemblyName("DynamicAssemblyExample");
AssemblyBuilder ab =
AssemblyBuilder.DefineDynamicAssembly(
aName,
AssemblyBuilderAccess.Run);
// The module name is usually the same as the assembly name.
ModuleBuilder mb = ab.DefineDynamicModule(aName.Name ?? "DynamicAssemblyExample");
TypeBuilder tb = mb.DefineType(
"MyDynamicType",
TypeAttributes.Public);
// Add a private field of type int (Int32).
FieldBuilder fbNumber = tb.DefineField(
"m_number",
typeof(int),
FieldAttributes.Private);
// Define a constructor that takes an integer argument and
// stores it in the private field.
Type[] parameterTypes = { typeof(int) };
ConstructorBuilder ctor1 = tb.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
parameterTypes);
ILGenerator ctor1IL = ctor1.GetILGenerator();
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before calling the base
// class constructor. Specify the default constructor of the
// base class (System.Object) by passing an empty array of
// types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0);
ConstructorInfo? ci = typeof(object).GetConstructor(Type.EmptyTypes);
ctor1IL.Emit(OpCodes.Call, ci!);
// Push the instance on the stack before pushing the argument
// that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0);
ctor1IL.Emit(OpCodes.Ldarg_1);
ctor1IL.Emit(OpCodes.Stfld, fbNumber);
ctor1IL.Emit(OpCodes.Ret);
// Define a default constructor that supplies a default value
// for the private field. For parameter types, pass the empty
// array of types or pass null.
ConstructorBuilder ctor0 = tb.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
Type.EmptyTypes);
ILGenerator ctor0IL = ctor0.GetILGenerator();
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before pushing the default
// value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0);
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42);
ctor0IL.Emit(OpCodes.Call, ctor1);
ctor0IL.Emit(OpCodes.Ret);
// Define a property named Number that gets and sets the private
// field.
//
// The last argument of DefineProperty is null, because the
// property has no parameters. (If you don't specify null, you must
// specify an array of Type objects. For a parameterless property,
// use the built-in array with no elements: Type.EmptyTypes)
PropertyBuilder pbNumber = tb.DefineProperty(
"Number",
PropertyAttributes.HasDefault,
typeof(int),
null);
// The property "set" and property "get" methods require a special
// set of attributes.
MethodAttributes getSetAttr = MethodAttributes.Public |
MethodAttributes.SpecialName | MethodAttributes.HideBySig;
// Define the "get" accessor method for Number. The method returns
// an integer and has no arguments. (Note that null could be
// used instead of Types.EmptyTypes)
MethodBuilder mbNumberGetAccessor = tb.DefineMethod(
"get_Number",
getSetAttr,
typeof(int),
Type.EmptyTypes);
ILGenerator numberGetIL = mbNumberGetAccessor.GetILGenerator();
// For an instance property, argument zero is the instance. Load the
// instance, then load the private field and return, leaving the
// field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0);
numberGetIL.Emit(OpCodes.Ldfld, fbNumber);
numberGetIL.Emit(OpCodes.Ret);
// Define the "set" accessor method for Number, which has no return
// type and takes one argument of type int (Int32).
MethodBuilder mbNumberSetAccessor = tb.DefineMethod(
"set_Number",
getSetAttr,
null,
new Type[] { typeof(int) });
ILGenerator numberSetIL = mbNumberSetAccessor.GetILGenerator();
// Load the instance and then the numeric argument, then store the
// argument in the field.
numberSetIL.Emit(OpCodes.Ldarg_0);
numberSetIL.Emit(OpCodes.Ldarg_1);
numberSetIL.Emit(OpCodes.Stfld, fbNumber);
numberSetIL.Emit(OpCodes.Ret);
// Last, map the "get" and "set" accessor methods to the
// PropertyBuilder. The property is now complete.
pbNumber.SetGetMethod(mbNumberGetAccessor);
pbNumber.SetSetMethod(mbNumberSetAccessor);
// Define a method that accepts an integer argument and returns
// the product of that integer and the private field m_number. This
// time, the array of parameter types is created on the fly.
MethodBuilder meth = tb.DefineMethod(
"MyMethod",
MethodAttributes.Public,
typeof(int),
new Type[] { typeof(int) });
ILGenerator methIL = meth.GetILGenerator();
// To retrieve the private instance field, load the instance it
// belongs to (argument zero). After loading the field, load the
// argument one and then multiply. Return from the method with
// the return value (the product of the two numbers) on the
// execution stack.
methIL.Emit(OpCodes.Ldarg_0);
methIL.Emit(OpCodes.Ldfld, fbNumber);
methIL.Emit(OpCodes.Ldarg_1);
methIL.Emit(OpCodes.Mul);
methIL.Emit(OpCodes.Ret);
// Finish the type.
Type? t = tb.CreateType();
// Because AssemblyBuilderAccess includes Run, the code can be
// executed immediately. Start by getting reflection objects for
// the method and the property.
MethodInfo? mi = t?.GetMethod("MyMethod");
PropertyInfo? pi = t?.GetProperty("Number");
// Create an instance of MyDynamicType using the default
// constructor.
object? o1 = null;
if (t is not null)
o1 = Activator.CreateInstance(t);
// Display the value of the property, then change it to 127 and
// display it again. Use null to indicate that the property
// has no index.
Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null));
pi?.SetValue(o1, 127, null);
Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null));
// Call MyMethod, passing 22, and display the return value, 22
// times 127. Arguments must be passed as an array, even when
// there is only one.
object[] arguments = { 22 };
Console.WriteLine("o1.MyMethod(22): {0}",
mi?.Invoke(o1, arguments));
// Create an instance of MyDynamicType using the constructor
// that specifies m_Number. The constructor is identified by
// matching the types in the argument array. In this case,
// the argument array is created on the fly. Display the
// property value.
object? o2 = null;
if (t is not null)
Activator.CreateInstance(t, new object[] { 5280 });
Console.WriteLine("o2.Number: {0}", pi?.GetValue(o2, null));
}
}
/* This code produces the following output:
o1.Number: 42
o1.Number: 127
o1.MyMethod(22): 2794
o2.Number: 5280
*/
open System
open System.Threading
open System.Reflection
open System.Reflection.Emit
// This code creates an assembly that contains one type,
// named "MyDynamicType", that has a private field, a property
// that gets and sets the private field, constructors that
// initialize the private field, and a method that multiplies
// a user-supplied number by the private field value and returns
// the result. In C# the type might look like this:
(*
public class MyDynamicType
{
private int m_number;
public MyDynamicType() : this(42) {}
public MyDynamicType(int initNumber)
{
m_number = initNumber;
}
public int Number
{
get { return m_number; }
set { m_number = value; }
}
public int MyMethod(int multiplier)
{
return m_number * multiplier;
}
}
*)
let assemblyName = new AssemblyName("DynamicAssemblyExample")
let assemblyBuilder =
AssemblyBuilder.DefineDynamicAssembly(
assemblyName,
AssemblyBuilderAccess.Run)
// The module name is usually the same as the assembly name.
let moduleBuilder =
assemblyBuilder.DefineDynamicModule(assemblyName.Name)
let typeBuilder =
moduleBuilder.DefineType(
"MyDynamicType",
TypeAttributes.Public)
// Add a private field of type int (Int32)
let fieldBuilderNumber =
typeBuilder.DefineField(
"m_number",
typeof<int>,
FieldAttributes.Private)
// Define a constructor1 that takes an integer argument and
// stores it in the private field.
let parameterTypes = [| typeof<int> |]
let ctor1 =
typeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
parameterTypes)
let ctor1IL = ctor1.GetILGenerator()
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before calling the base
// class constructor. Specify the default constructor of the
// base class (System.Object) by passing an empty array of
// types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Call,
typeof<obj>.GetConstructor(Type.EmptyTypes))
// Push the instance on the stack before pushing the argument
// that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Ldarg_1)
ctor1IL.Emit(OpCodes.Stfld, fieldBuilderNumber)
ctor1IL.Emit(OpCodes.Ret)
// Define a default constructor1 that supplies a default value
// for the private field. For parameter types, pass the empty
// array of types or pass null.
let ctor0 =
typeBuilder.DefineConstructor(
MethodAttributes.Public,
CallingConventions.Standard,
Type.EmptyTypes)
let ctor0IL = ctor0.GetILGenerator()
// For a constructor, argument zero is a reference to the new
// instance. Push it on the stack before pushing the default
// value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0)
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42)
ctor0IL.Emit(OpCodes.Call, ctor1)
ctor0IL.Emit(OpCodes.Ret)
// Define a property named Number that gets and sets the private
// field.
//
// The last argument of DefineProperty is null, because the
// property has no parameters. (If you don't specify null, you must
// specify an array of Type objects. For a parameterless property,
// use the built-in array with no elements: Type.EmptyTypes)
let propertyBuilderNumber =
typeBuilder.DefineProperty(
"Number",
PropertyAttributes.HasDefault,
typeof<int>,
null)
// The property "set" and property "get" methods require a special
// set of attributes.
let getSetAttr = MethodAttributes.Public ||| MethodAttributes.SpecialName ||| MethodAttributes.HideBySig
// Define the "get" accessor method for Number. The method returns
// an integer and has no arguments. (Note that null could be
// used instead of Types.EmptyTypes)
let methodBuilderNumberGetAccessor =
typeBuilder.DefineMethod(
"get_number",
getSetAttr,
typeof<int>,
Type.EmptyTypes)
let numberGetIL =
methodBuilderNumberGetAccessor.GetILGenerator()
// For an instance property, argument zero ir the instance. Load the
// instance, then load the private field and return, leaving the
// field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0)
numberGetIL.Emit(OpCodes.Ldfld, fieldBuilderNumber)
numberGetIL.Emit(OpCodes.Ret)
// Define the "set" accessor method for Number, which has no return
// type and takes one argument of type int (Int32).
let methodBuilderNumberSetAccessor =
typeBuilder.DefineMethod(
"set_number",
getSetAttr,
null,
[| typeof<int> |])
let numberSetIL =
methodBuilderNumberSetAccessor.GetILGenerator()
// Load the instance and then the numeric argument, then store the
// argument in the field
numberSetIL.Emit(OpCodes.Ldarg_0)
numberSetIL.Emit(OpCodes.Ldarg_1)
numberSetIL.Emit(OpCodes.Stfld, fieldBuilderNumber)
numberSetIL.Emit(OpCodes.Ret)
// Last, map the "get" and "set" accessor methods to the
// PropertyBuilder. The property is now complete.
propertyBuilderNumber.SetGetMethod(methodBuilderNumberGetAccessor)
propertyBuilderNumber.SetSetMethod(methodBuilderNumberSetAccessor)
// Define a method that accepts an integer argument and returns
// the product of that integer and the private field m_number. This
// time, the array of parameter types is created on the fly.
let methodBuilder =
typeBuilder.DefineMethod(
"MyMethod",
MethodAttributes.Public,
typeof<int>,
[| typeof<int> |])
let methodIL = methodBuilder.GetILGenerator()
// To retrieve the private instance field, load the instance it
// belongs to (argument zero). After loading the field, load the
// argument one and then multiply. Return from the method with
// the return value (the product of the two numbers) on the
// execution stack.
methodIL.Emit(OpCodes.Ldarg_0)
methodIL.Emit(OpCodes.Ldfld, fieldBuilderNumber)
methodIL.Emit(OpCodes.Ldarg_1)
methodIL.Emit(OpCodes.Mul)
methodIL.Emit(OpCodes.Ret)
// Finish the type
let typ = typeBuilder.CreateType()
// Because AssemblyBuilderAccess includes Run, the code can be
// executed immediately. Start by getting reflection objects for
// the method and the property.
let methodInfo = typ.GetMethod("MyMethod")
let propertyInfo = typ.GetProperty("Number")
// Create an instance of MyDynamicType using the default
// constructor.
let obj1 = Activator.CreateInstance(typ)
// Display the value of the property, then change it to 127 and
// display it again. Use null to indicate that the property
// has no index.
printfn "obj1.Number: %A" (propertyInfo.GetValue(obj1, null))
propertyInfo.SetValue(obj1, 127, null)
printfn "obj1.Number: %A" (propertyInfo.GetValue(obj1, null))
// Call MyMethod, pasing 22, and display the return value, 22
// times 127. Arguments must be passed as an array, even when
// there is only one.
let arguments: obj array = [| 22 |]
printfn "obj1.MyMethod(22): %A" (methodInfo.Invoke(obj1, arguments))
// Create an instance of MyDynamicType using the constructor
// that specifies m_Number. The constructor is identified by
// matching the types in the argument array. In this case,
// the argument array is created on the fly. Display the
// property value.
let constructorArguments: obj array = [| 5280 |]
let obj2 = Activator.CreateInstance(typ, constructorArguments)
printfn "obj2.Number: %A" (propertyInfo.GetValue(obj2, null))
(* This code produces the following output:
obj1.Number: 42
obj1.Number: 127
obj1.MyMethod(22): 2794
obj1.Number: 5280
*)
Imports System.Reflection
Imports System.Reflection.Emit
Class DemoAssemblyBuilder
Public Shared Sub Main()
' This code creates an assembly that contains one type,
' named "MyDynamicType", that has a private field, a property
' that gets and sets the private field, constructors that
' initialize the private field, and a method that multiplies
' a user-supplied number by the private field value and returns
' the result. The code might look like this in Visual Basic:
'
'Public Class MyDynamicType
' Private m_number As Integer
'
' Public Sub New()
' Me.New(42)
' End Sub
'
' Public Sub New(ByVal initNumber As Integer)
' m_number = initNumber
' End Sub
'
' Public Property Number As Integer
' Get
' Return m_number
' End Get
' Set
' m_Number = Value
' End Set
' End Property
'
' Public Function MyMethod(ByVal multiplier As Integer) As Integer
' Return m_Number * multiplier
' End Function
'End Class
Dim aName As New AssemblyName("DynamicAssemblyExample")
Dim ab As AssemblyBuilder = _
AssemblyBuilder.DefineDynamicAssembly( _
aName, _
AssemblyBuilderAccess.Run)
' The module name is usually the same as the assembly name.
Dim mb As ModuleBuilder = ab.DefineDynamicModule( _
aName.Name)
Dim tb As TypeBuilder = _
mb.DefineType("MyDynamicType", TypeAttributes.Public)
' Add a private field of type Integer (Int32).
Dim fbNumber As FieldBuilder = tb.DefineField( _
"m_number", _
GetType(Integer), _
FieldAttributes.Private)
' Define a constructor that takes an integer argument and
' stores it in the private field.
Dim parameterTypes() As Type = { GetType(Integer) }
Dim ctor1 As ConstructorBuilder = _
tb.DefineConstructor( _
MethodAttributes.Public, _
CallingConventions.Standard, _
parameterTypes)
Dim ctor1IL As ILGenerator = ctor1.GetILGenerator()
' For a constructor, argument zero is a reference to the new
' instance. Push it on the stack before calling the base
' class constructor. Specify the default constructor of the
' base class (System.Object) by passing an empty array of
' types (Type.EmptyTypes) to GetConstructor.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Call, _
GetType(Object).GetConstructor(Type.EmptyTypes))
' Push the instance on the stack before pushing the argument
' that is to be assigned to the private field m_number.
ctor1IL.Emit(OpCodes.Ldarg_0)
ctor1IL.Emit(OpCodes.Ldarg_1)
ctor1IL.Emit(OpCodes.Stfld, fbNumber)
ctor1IL.Emit(OpCodes.Ret)
' Define a default constructor that supplies a default value
' for the private field. For parameter types, pass the empty
' array of types or pass Nothing.
Dim ctor0 As ConstructorBuilder = tb.DefineConstructor( _
MethodAttributes.Public, _
CallingConventions.Standard, _
Type.EmptyTypes)
Dim ctor0IL As ILGenerator = ctor0.GetILGenerator()
' For a constructor, argument zero is a reference to the new
' instance. Push it on the stack before pushing the default
' value on the stack, then call constructor ctor1.
ctor0IL.Emit(OpCodes.Ldarg_0)
ctor0IL.Emit(OpCodes.Ldc_I4_S, 42)
ctor0IL.Emit(OpCodes.Call, ctor1)
ctor0IL.Emit(OpCodes.Ret)
' Define a property named Number that gets and sets the private
' field.
'
' The last argument of DefineProperty is Nothing, because the
' property has no parameters. (If you don't specify Nothing, you must
' specify an array of Type objects. For a parameterless property,
' use the built-in array with no elements: Type.EmptyTypes)
Dim pbNumber As PropertyBuilder = tb.DefineProperty( _
"Number", _
PropertyAttributes.HasDefault, _
GetType(Integer), _
Nothing)
' The property Set and property Get methods require a special
' set of attributes.
Dim getSetAttr As MethodAttributes = _
MethodAttributes.Public Or MethodAttributes.SpecialName _
Or MethodAttributes.HideBySig
' Define the "get" accessor method for Number. The method returns
' an integer and has no arguments. (Note that Nothing could be
' used instead of Types.EmptyTypes)
Dim mbNumberGetAccessor As MethodBuilder = tb.DefineMethod( _
"get_Number", _
getSetAttr, _
GetType(Integer), _
Type.EmptyTypes)
Dim numberGetIL As ILGenerator = mbNumberGetAccessor.GetILGenerator()
' For an instance property, argument zero is the instance. Load the
' instance, then load the private field and return, leaving the
' field value on the stack.
numberGetIL.Emit(OpCodes.Ldarg_0)
numberGetIL.Emit(OpCodes.Ldfld, fbNumber)
numberGetIL.Emit(OpCodes.Ret)
' Define the "set" accessor method for Number, which has no return
' type and takes one argument of type Integer (Int32).
Dim mbNumberSetAccessor As MethodBuilder = _
tb.DefineMethod( _
"set_Number", _
getSetAttr, _
Nothing, _
New Type() { GetType(Integer) })
Dim numberSetIL As ILGenerator = mbNumberSetAccessor.GetILGenerator()
' Load the instance and then the numeric argument, then store the
' argument in the field.
numberSetIL.Emit(OpCodes.Ldarg_0)
numberSetIL.Emit(OpCodes.Ldarg_1)
numberSetIL.Emit(OpCodes.Stfld, fbNumber)
numberSetIL.Emit(OpCodes.Ret)
' Last, map the "get" and "set" accessor methods to the
' PropertyBuilder. The property is now complete.
pbNumber.SetGetMethod(mbNumberGetAccessor)
pbNumber.SetSetMethod(mbNumberSetAccessor)
' Define a method that accepts an integer argument and returns
' the product of that integer and the private field m_number. This
' time, the array of parameter types is created on the fly.
Dim meth As MethodBuilder = tb.DefineMethod( _
"MyMethod", _
MethodAttributes.Public, _
GetType(Integer), _
New Type() { GetType(Integer) })
Dim methIL As ILGenerator = meth.GetILGenerator()
' To retrieve the private instance field, load the instance it
' belongs to (argument zero). After loading the field, load the
' argument one and then multiply. Return from the method with
' the return value (the product of the two numbers) on the
' execution stack.
methIL.Emit(OpCodes.Ldarg_0)
methIL.Emit(OpCodes.Ldfld, fbNumber)
methIL.Emit(OpCodes.Ldarg_1)
methIL.Emit(OpCodes.Mul)
methIL.Emit(OpCodes.Ret)
' Finish the type.
Dim t As Type = tb.CreateType()
' Because AssemblyBuilderAccess includes Run, the code can be
' executed immediately. Start by getting reflection objects for
' the method and the property.
Dim mi As MethodInfo = t.GetMethod("MyMethod")
Dim pi As PropertyInfo = t.GetProperty("Number")
' Create an instance of MyDynamicType using the default
' constructor.
Dim o1 As Object = Activator.CreateInstance(t)
' Display the value of the property, then change it to 127 and
' display it again. Use Nothing to indicate that the property
' has no index.
Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))
pi.SetValue(o1, 127, Nothing)
Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, Nothing))
' Call MyMethod, passing 22, and display the return value, 22
' times 127. Arguments must be passed as an array, even when
' there is only one.
Dim arguments() As Object = { 22 }
Console.WriteLine("o1.MyMethod(22): {0}", _
mi.Invoke(o1, arguments))
' Create an instance of MyDynamicType using the constructor
' that specifies m_Number. The constructor is identified by
' matching the types in the argument array. In this case,
' the argument array is created on the fly. Display the
' property value.
Dim o2 As Object = Activator.CreateInstance(t, _
New Object() { 5280 })
Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, Nothing))
End Sub
End Class
' This code produces the following output:
'
'o1.Number: 42
'o1.Number: 127
'o1.MyMethod(22): 2794
'o2.Number: 5280
Comentários
Para obter mais informações sobre essa API, consulte Comentários da API complementar para AssemblyBuilder.
Construtores
AssemblyBuilder() |
Inicializa uma nova instância da classe AssemblyBuilder. |
Propriedades
CodeBase |
Obsoleto.
Obtém o local do assembly como especificado originalmente (como em um objeto AssemblyName). |
CodeBase |
Obsoleto.
Obsoleto.
Obtém o local do assembly como especificado originalmente, por exemplo, em um objeto AssemblyName. (Herdado de Assembly) |
CustomAttributes |
Obtém uma coleção que contém os atributos personalizados deste assembly. (Herdado de Assembly) |
DefinedTypes |
Define e representa um assembly dinâmico. |
DefinedTypes |
Obtém uma coleção dos tipos definidos nesse assembly. (Herdado de Assembly) |
EntryPoint |
Retorna o ponto de entrada desse assembly. |
EntryPoint |
Obtém o ponto de entrada desse assembly. (Herdado de Assembly) |
EscapedCodeBase |
Obsoleto.
Obsoleto.
Obtém o URI, incluindo caracteres de escape, que representa a base de código. (Herdado de Assembly) |
Evidence |
Obtém a evidência para esse assembly. |
Evidence |
Obtém a evidência para esse assembly. (Herdado de Assembly) |
ExportedTypes |
Obtém uma coleção dos tipos públicos definidos nesse assembly visíveis fora do assembly. (Herdado de Assembly) |
FullName |
Obtém o nome de exibição do assembly dinâmico atual. |
FullName |
Obtém o nome de exibição do assembly. (Herdado de Assembly) |
GlobalAssemblyCache |
Obsoleto.
Obtém um valor que indica se o assembly foi carregado do cache de assembly global. |
GlobalAssemblyCache |
Obsoleto.
Obtém um valor que indica se o assembly foi carregado do cache de assembly global (somente .NET Framework). (Herdado de Assembly) |
HostContext |
Obtém o contexto do host em que o assembly dinâmico está sendo criado. |
HostContext |
Obtém o contexto de host com o qual o assembly foi carregado. (Herdado de Assembly) |
ImageRuntimeVersion |
Obtém a versão do Common Language Runtime que será salvo no arquivo que contém o manifesto. |
ImageRuntimeVersion |
Obtém uma cadeia de caracteres que representa a versão do CLR (Common Language Runtime) salva no arquivo que contém o manifesto. (Herdado de Assembly) |
IsCollectible |
Obtém um valor que indica se esse assembly dinâmico é mantido em um colecionável AssemblyLoadContext. |
IsCollectible |
Obtém um valor que indica se este assembly é mantido em uma coleção AssemblyLoadContext. (Herdado de Assembly) |
IsDynamic |
Obtém um valor que indica que o assembly atual é um assembly dinâmico. |
IsDynamic |
Obtém um valor que indica se o assembly atual foi gerado dinamicamente no processo atual através da emissão de reflexo. (Herdado de Assembly) |
IsFullyTrusted |
Obtém um valor que indica se o assembly atual é carregado com confiança total. (Herdado de Assembly) |
Location |
Obtém o local, no formato de base de código, do arquivo carregado que contém o manifesto, caso não tenha sido feita cópia de sombra dele. |
Location |
Obtém o caminho completo ou uma localização UNC do arquivo carregado que contém o manifesto. (Herdado de Assembly) |
ManifestModule |
Obtém o módulo no AssemblyBuilder atual que contém o manifesto do assembly. |
ManifestModule |
Obtém o módulo que contém o manifesto do assembly atual. (Herdado de Assembly) |
Modules |
Define e representa um assembly dinâmico. |
Modules |
Obtém uma coleção que contém os módulos neste assembly. (Herdado de Assembly) |
PermissionSet |
Obtém o conjunto de concessões do assembly dinâmico atual. |
PermissionSet |
Obtém o conjunto de concessões do assembly atual. (Herdado de Assembly) |
ReflectionOnly |
Obtém um valor que indica se o assembly dinâmico está no contexto de somente reflexão. |
ReflectionOnly |
Obtém um valor Boolean que indica se esse assembly foi carregado no contexto de somente reflexão. (Herdado de Assembly) |
SecurityRuleSet |
Obtém um valor que indica qual conjunto de regras de segurança o CLR (Common Language Runtime) impõe a este assembly. |
SecurityRuleSet |
Obtém um valor que indica qual conjunto de regras de segurança o CLR (Common Language Runtime) impõe a este assembly. (Herdado de Assembly) |
Métodos
AddResourceFile(String, String) |
Adiciona um arquivo de recurso existente a esse assembly. |
AddResourceFile(String, String, ResourceAttributes) |
Adiciona um arquivo de recurso existente a esse assembly. |
CreateInstance(String) |
Localiza o tipo especificado desse assembly e cria uma instância dele usando o ativador de sistema, usando a pesquisa que diferencia maiúsculas de minúsculas. (Herdado de Assembly) |
CreateInstance(String, Boolean) |
Localiza o tipo especificado desse assembly e cria uma instância dele usando o ativador de sistema, com pesquisa que diferencia maiúsculas de minúsculas opcional. (Herdado de Assembly) |
CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) |
Localiza o tipo especificado desse assembly e cria uma instância dele usando o ativador do sistema, com a pesquisa opcional que diferencia maiúsculas de minúsculas e com a cultura especificada, os argumentos e os atributos de associação e ativação. (Herdado de Assembly) |
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) |
Define um assembly dinâmico que tem o nome e os direitos de acesso especificados. |
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>) |
Define um novo assembly que tem o nome, os direitos de acesso e os atributos especificados. |
DefineDynamicModule(String) |
Define um módulo dinâmico transitório nomeado nesse assembly. |
DefineDynamicModule(String, Boolean) |
Define o módulo dinâmico transitório nomeado neste assembly e especifica se as informações de símbolo devem ser emitidas. |
DefineDynamicModule(String, String) |
Define um módulo dinâmico persistente com o nome fornecido que será salvo no arquivo especificado. Nenhuma informação de símbolo é emitida. |
DefineDynamicModule(String, String, Boolean) |
Define um módulo dinâmico persistente, especificando o nome do módulo, o nome do arquivo no qual o módulo será salvo e se as informações de símbolo deverão ser emitidas usando o gravador de símbolo padrão. |
DefineDynamicModuleCore(String) |
Quando substituído em uma classe derivada, define um módulo dinâmico neste assembly. |
DefineResource(String, String, String) |
Define um recurso gerenciado autônomo para esse assembly com o atributo de recurso público padrão. |
DefineResource(String, String, String, ResourceAttributes) |
Define um recurso autônomo gerenciado para esse assembly. Atributos podem ser especificados para o recurso gerenciado. |
DefineUnmanagedResource(Byte[]) |
Define um recurso não gerenciado para este assembly como um blob de bytes opaco. |
DefineUnmanagedResource(String) |
Define um arquivo de recurso não gerenciado para este assembly, considerando o nome do arquivo de recurso. |
DefineVersionInfoResource() |
Define um recurso de informações de versão não gerenciada usando as informações especificadas no objeto AssemblyName do assembly e nos atributos personalizados do assembly. |
DefineVersionInfoResource(String, String, String, String, String) |
Define um recurso de informações de versão não gerenciada para este assembly com as especificações determinadas. |
Equals(Object) |
Retorna um valor que indica se esta instância é igual ao objeto especificado. |
Equals(Object) |
Determina se este assembly e o objeto especificado são iguais. (Herdado de Assembly) |
GetCustomAttributes(Boolean) |
Retorna todos os atributos personalizados que foram aplicados ao AssemblyBuilder atual. |
GetCustomAttributes(Boolean) |
Obtém todos os atributos personalizados para esse assembly. (Herdado de Assembly) |
GetCustomAttributes(Type, Boolean) |
Retorna todos os atributos personalizados que foram aplicados ao AssemblyBuilder atual e que derivam de um tipo de atributo especificado. |
GetCustomAttributes(Type, Boolean) |
Obtém os atributos personalizados para esse assembly conforme especificado pelo tipo. (Herdado de Assembly) |
GetCustomAttributesData() |
Retorna objetos CustomAttributeData que contêm informações sobre os atributos que foram aplicados ao AssemblyBuilder atual. |
GetCustomAttributesData() |
Retorna informações sobre os atributos que foram aplicados ao Assemblyatual, expressos como objetos CustomAttributeData . (Herdado de Assembly) |
GetDynamicModule(String) |
Retorna o módulo dinâmico com o nome especificado. |
GetDynamicModuleCore(String) |
Quando substituído em uma classe derivada, retorna o módulo dinâmico com o nome especificado. |
GetExportedTypes() |
Obtém os tipos exportados definidos neste assembly. |
GetExportedTypes() |
Obtém os tipos públicos definidos nesse assembly que são visíveis fora do assembly. (Herdado de Assembly) |
GetFile(String) |
Obtém um FileStream para o arquivo especificado na tabela de arquivo do manifesto desse assembly. |
GetFile(String) |
Obtém um FileStream para o arquivo especificado na tabela de arquivo do manifesto desse assembly. (Herdado de Assembly) |
GetFiles() |
Obtém os arquivos na tabela de arquivo de um manifesto do assembly. (Herdado de Assembly) |
GetFiles(Boolean) |
Obtém os arquivos na tabela de arquivos de um manifesto do assembly, especificando se deseja-se incluir os módulos de recursos. |
GetFiles(Boolean) |
Obtém os arquivos na tabela de arquivos de um manifesto do assembly, especificando se deseja-se incluir os módulos de recursos. (Herdado de Assembly) |
GetForwardedTypes() |
Define e representa um assembly dinâmico. (Herdado de Assembly) |
GetHashCode() |
Retorna o código hash para a instância. |
GetHashCode() |
Retorna o código hash para a instância. (Herdado de Assembly) |
GetLoadedModules() |
Obtém todos os módulos carregados que fazem parte desse assembly. (Herdado de Assembly) |
GetLoadedModules(Boolean) |
Retorna todos os módulos carregados que fazem parte desse assembly e, opcionalmente, inclui módulos de recursos. |
GetLoadedModules(Boolean) |
Obtém todos os módulos carregados que fazem parte desse assembly, especificando se os módulos de recursos devem ser incluídos. (Herdado de Assembly) |
GetManifestResourceInfo(String) |
Retorna informações sobre como o recurso em questão foi persistido. |
GetManifestResourceNames() |
Carrega o recurso de manifesto especificado desse assembly. |
GetManifestResourceStream(String) |
Carrega o recurso de manifesto especificado desse assembly. |
GetManifestResourceStream(Type, String) |
Carrega o recurso de manifesto especificado, o escopo pelo namespace do tipo especificado, desse assembly. |
GetManifestResourceStream(Type, String) |
Carrega o recurso de manifesto especificado, o escopo pelo namespace do tipo especificado, desse assembly. (Herdado de Assembly) |
GetModule(String) |
Obtém o módulo especificado nesse assembly. |
GetModule(String) |
Obtém o módulo especificado nesse assembly. (Herdado de Assembly) |
GetModules() |
Obtém todos os módulos que fazem parte desse assembly. (Herdado de Assembly) |
GetModules(Boolean) |
Obtém todos os módulos que fazem parte desse assembly e, opcionalmente, inclui módulos de recursos. |
GetModules(Boolean) |
Obtém todos os módulos que fazem parte desse assembly, especificando se os módulos de recursos devem ser incluídos. (Herdado de Assembly) |
GetName() |
Obtém um AssemblyName para esse assembly. (Herdado de Assembly) |
GetName(Boolean) |
Obtém o AssemblyName, que foi especificado quando o assembly dinâmico atual foi criado e define a base de código como especificado. |
GetName(Boolean) |
Obtém um AssemblyName para esse assembly, definindo a base de código como especificado por |
GetObjectData(SerializationInfo, StreamingContext) |
Obsoleto.
Obtém informações de serialização com todos os dados necessários para recriar uma instância desse assembly. (Herdado de Assembly) |
GetReferencedAssemblies() |
Obtém uma lista incompleta de objetos AssemblyName para os assemblies que são referenciados por este AssemblyBuilder. |
GetReferencedAssemblies() |
Obtém os objetos AssemblyName para todos os assemblies referenciados por esse assembly. (Herdado de Assembly) |
GetSatelliteAssembly(CultureInfo) |
Obtém o assembly satélite para a cultura especificada. |
GetSatelliteAssembly(CultureInfo) |
Obtém o assembly satélite para a cultura especificada. (Herdado de Assembly) |
GetSatelliteAssembly(CultureInfo, Version) |
Obtém a versão especificada do assembly satélite para a cultura especificada. |
GetSatelliteAssembly(CultureInfo, Version) |
Obtém a versão especificada do assembly satélite para a cultura especificada. (Herdado de Assembly) |
GetType() |
Define e representa um assembly dinâmico. (Herdado de Assembly) |
GetType(String) |
Obtém o objeto Type com o nome especificado na instância do assembly. (Herdado de Assembly) |
GetType(String, Boolean) |
Obtém o objeto Type com o nome especificado na instância do assembly e, opcionalmente, lança uma exceção se o tipo não for encontrado. (Herdado de Assembly) |
GetType(String, Boolean, Boolean) |
Obtém o tipo especificado dos tipos que foram definidos e criados no AssemblyBuilder atual. |
GetType(String, Boolean, Boolean) |
Obtém o objeto Type com o nome especificado na instância do assembly, com a opção de ignorar a diferença entre maiúsculas e minúsculas e de gerar uma exceção se o tipo não for encontrado. (Herdado de Assembly) |
GetTypes() |
Obtém todos os tipos definidos neste assembly. (Herdado de Assembly) |
IsDefined(Type, Boolean) |
Retorna um valor que indica se uma ou mais instâncias do tipo de atributo especificado será aplicada a esse membro. |
IsDefined(Type, Boolean) |
Indica se um atributo especificado foi ou não foi aplicado ao assembly. (Herdado de Assembly) |
LoadModule(String, Byte[]) |
Carrega o módulo, interno a esse assembly, com uma imagem baseada no formato COFF que contém um módulo emitido ou um arquivo de recurso. (Herdado de Assembly) |
LoadModule(String, Byte[], Byte[]) |
Carrega o módulo, interno a esse assembly, com uma imagem baseada no formato COFF que contém um módulo emitido ou um arquivo de recurso. Os bytes brutos que representam os símbolos para o módulo também são carregados. (Herdado de Assembly) |
MemberwiseClone() |
Cria uma cópia superficial do Object atual. (Herdado de Object) |
Save(String) |
Salva esse assembly dinâmico em disco. |
Save(String, PortableExecutableKinds, ImageFileMachine) |
Salva esse assembly dinâmico no disco, especificando a natureza do código nos executáveis do assembly e na plataforma de destino. |
SetCustomAttribute(ConstructorInfo, Byte[]) |
Defina um atributo personalizado neste assembly usando um blob de atributos personalizados especificado. |
SetCustomAttribute(CustomAttributeBuilder) |
Defina um atributo personalizado neste assembly usando um construtor de atributos personalizados. |
SetCustomAttributeCore(ConstructorInfo, ReadOnlySpan<Byte>) |
Quando substituído em uma classe derivada, define um atributo personalizado neste assembly. |
SetEntryPoint(MethodInfo) |
Define o ponto de entrada para este assembly dinâmico, supondo que um aplicativo de console está sendo compilado. |
SetEntryPoint(MethodInfo, PEFileKinds) |
Define o ponto de entrada para este assembly e define o tipo de arquivo PE (executável portátil) que está sendo compilado. |
ToString() |
Retorna o nome completo do assembly, também conhecido como o nome de exibição. (Herdado de Assembly) |
Eventos
ModuleResolve |
Ocorre quando o carregador de classe do Common Language Runtime não é capaz de resolver uma referência a um módulo interno de um assembly por meios normais. (Herdado de Assembly) |
Implantações explícitas de interface
_Assembly.GetType() |
Retorna o tipo da instância atual. (Herdado de Assembly) |
_AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição. |
_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera as informações do tipo de um objeto, que podem ser usadas para obter informações de tipo para uma interface. |
_AssemblyBuilder.GetTypeInfoCount(UInt32) |
Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1). |
_AssemblyBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornece acesso a propriedades e métodos expostos por um objeto. |
ICustomAttributeProvider.GetCustomAttributes(Boolean) |
Retorna uma matriz de todos os atributos personalizados definidos neste membro, exceto atributos nomeados ou então uma matriz vazia, se não houver nenhum atributo personalizado. (Herdado de Assembly) |
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) |
Retorna uma matriz de atributos personalizados definidos neste membro, identificados por tipo ou então uma matriz vazia, se não houver nenhum atributo personalizado desse tipo. (Herdado de Assembly) |
ICustomAttributeProvider.IsDefined(Type, Boolean) |
Indica se uma ou mais instâncias de |
Métodos de Extensão
GetExportedTypes(Assembly) |
Define e representa um assembly dinâmico. |
GetModules(Assembly) |
Define e representa um assembly dinâmico. |
GetTypes(Assembly) |
Define e representa um assembly dinâmico. |
GetCustomAttribute(Assembly, Type) |
Recupera um atributo personalizado de um tipo especificado aplicado a um assembly especificado. |
GetCustomAttribute<T>(Assembly) |
Recupera um atributo personalizado de um tipo especificado aplicado a um assembly especificado. |
GetCustomAttributes(Assembly) |
Recupera uma coleção de atributos personalizados que são aplicados a um assembly especificado. |
GetCustomAttributes(Assembly, Type) |
Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um assembly especificado. |
GetCustomAttributes<T>(Assembly) |
Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um assembly especificado. |
IsDefined(Assembly, Type) |
Indica se os atributos personalizados de um tipo especificados são aplicados a um assembly especificado. |
TryGetRawMetadata(Assembly, Byte*, Int32) |
Recupera a seção de metadados do assembly, para uso com MetadataReader. |
Aplica-se a
Confira também
Comentários
https://aka.ms/ContentUserFeedback.
Em breve: Ao longo de 2024, eliminaremos os problemas do GitHub como o mecanismo de comentários para conteúdo e o substituiremos por um novo sistema de comentários. Para obter mais informações, consulteEnviar e exibir comentários de