AssemblyBuilder Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет и представляет динамическую сборку.
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
- Наследование
- Производный
- Атрибуты
- Реализации
Примеры
В следующем примере кода показано, как определить и использовать динамическую сборку. Пример сборки содержит один тип , MyDynamicType
который имеет частное поле, свойство, которое получает и задает частное поле, конструкторы, инициализирующие частное поле, и метод, который умножает предоставленное пользователем число на значение частного поля и возвращает результат.
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
Комментарии
Дополнительные сведения об этом API см. в разделе Дополнительные примечания API для AssemblyBuilder.
Конструкторы
AssemblyBuilder() |
Инициализирует новый экземпляр класса AssemblyBuilder. |
Свойства
CodeBase |
Устаревшие..
Получает первоначально заданное расположение сборки (например, в объекте AssemblyName). |
CodeBase |
Устаревшие..
Устаревшие..
Получает первоначально заданное расположение сборки, например в объекте AssemblyName. (Унаследовано от Assembly) |
CustomAttributes |
Получает коллекцию, содержащую пользовательские атрибуты этой сборки. (Унаследовано от Assembly) |
DefinedTypes |
Определяет и представляет динамическую сборку. |
DefinedTypes |
Получает коллекцию типов, определенных в этой сборке. (Унаследовано от Assembly) |
EntryPoint |
Возвращает точку входа для этой сборки. |
EntryPoint |
Получает точку входа для этой сборки. (Унаследовано от Assembly) |
EscapedCodeBase |
Устаревшие..
Устаревшие..
Получает универсальный код доступа (URI), предоставляющий базовый код, включая escape-символы. (Унаследовано от Assembly) |
Evidence |
Получает свидетельство для этой сборки. |
Evidence |
Получает свидетельство для этой сборки. (Унаследовано от Assembly) |
ExportedTypes |
Получает коллекцию открытых типов, определенных в этой сборке и видимых за ее пределами. (Унаследовано от Assembly) |
FullName |
Получает отображаемое имя текущей динамической сборки. |
FullName |
Получает отображаемое имя сборки. (Унаследовано от Assembly) |
GlobalAssemblyCache |
Устаревшие..
Получает значение, указывающее, была ли сборка загружена из глобального кэша сборок. |
GlobalAssemblyCache |
Устаревшие..
Возвращает значение, указывающее, была ли сборка загружена из глобального кэша сборок (только платформа .NET Framework). (Унаследовано от Assembly) |
HostContext |
Получает контекст узла, где создается динамическая сборка. |
HostContext |
Получает контекст хост-сайта, с которым была загружена сборка. (Унаследовано от Assembly) |
ImageRuntimeVersion |
Возвращает версию среды CLR, которая будет сохранена в файле, содержащем манифест. |
ImageRuntimeVersion |
Получает строку, представляющую версию общеязыковой среды выполнения (CLR), сохраненной в файле, содержащем манифест. (Унаследовано от Assembly) |
IsCollectible |
Возвращает значение, указывающее, хранится ли динамическая сборка в коллекционируемых объектах AssemblyLoadContext. |
IsCollectible |
Получает значение, указывающее, содержится ли объект в забираемом контексте AssemblyLoadContext. (Унаследовано от Assembly) |
IsDynamic |
Получает значение, указывающее, что текущая сборка является динамической. |
IsDynamic |
Получает значение, определяющее, была ли текущая сборка создана динамически в текущем процессе с помощью отражения. (Унаследовано от Assembly) |
IsFullyTrusted |
Получает значение, указывающее, загружена ли текущая сборка с полным доверием. (Унаследовано от Assembly) |
Location |
Возвращает расположение (в формате базы кода) загруженного файла, содержащего манифест, если он не является теневой копией. |
Location |
Получает полный путь либо UNC для расположения загруженного файла, содержащего манифест. (Унаследовано от Assembly) |
ManifestModule |
Получает модуль в текущем AssemblyBuilder, содержащий манифест сборки. |
ManifestModule |
Возвращает модуль, содержащий манифест текущей сборки. (Унаследовано от Assembly) |
Modules |
Определяет и представляет динамическую сборку. |
Modules |
Получает коллекцию, содержащую модули в этой сборке. (Унаследовано от Assembly) |
PermissionSet |
Получает набор разрешений текущей динамической сборки. |
PermissionSet |
Получает набор разрешений текущей сборки. (Унаследовано от Assembly) |
ReflectionOnly |
Получает значение, которое указывает, находится ли эта динамическая сборка в контексте только отражения. |
ReflectionOnly |
Возвращает значение Boolean, которое указывает, была ли эта сборка загружена в контекст, предназначенный только для отражения. (Унаследовано от Assembly) |
SecurityRuleSet |
Получает значение, указывающее набор правил безопасности, которые применяются средой CLR к данной сборке. |
SecurityRuleSet |
Получает значение, указывающее набор правил безопасности, которые применяются средой CLR к данной сборке. (Унаследовано от Assembly) |
Методы
AddResourceFile(String, String) |
Добавляет существующий файл ресурсов в эту сборку. |
AddResourceFile(String, String, ResourceAttributes) |
Добавляет существующий файл ресурсов в эту сборку. |
CreateInstance(String) |
С помощью поиска с учетом регистра находит заданный тип в этой сборке и создает его экземпляр, используя абстрактный метод. (Унаследовано от Assembly) |
CreateInstance(String, Boolean) |
При помощи необязательного поиска с учетом регистра находит заданный тип в этой сборке и создает его экземпляр, используя абстрактный метод. (Унаследовано от Assembly) |
CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) |
Находит в сборке указанный тип и создает его экземпляр с использованием системного активатора при помощи необязательного поиска с учетом регистра и с заданными аргументами, культурой, а также атрибутами привязки и активации. (Унаследовано от Assembly) |
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) |
Определяет динамическую сборку, которая имеет указанные имя и права доступа. |
DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>) |
Определяет новую сборку, которая имеет указанные имя, права доступа и атрибуты. |
DefineDynamicModule(String) |
Определяет именованный временный динамический модуль в этой сборке. |
DefineDynamicModule(String, Boolean) |
Определяет именованный временный динамический модуль в данной сборке и указывает, требуется ли создавать данные символов. |
DefineDynamicModule(String, String) |
Определяет сохраняемый динамический модуль с заданным именем, который будет сохранен в указанном файле. Данные символов не созданы. |
DefineDynamicModule(String, String, Boolean) |
Определяет сохраняемый динамический модуль с указанием имени модуля, имени файла, в котором модуль будет сохранен, и необходимости создания символьной информации с помощью модуля записи символов по умолчанию. |
DefineDynamicModuleCore(String) |
При переопределении в производном классе определяет динамический модуль в этой сборке. |
DefineResource(String, String, String) |
Определяет автономный управляемый ресурс для данной сборки с атрибутом открытого ресурса по умолчанию. |
DefineResource(String, String, String, ResourceAttributes) |
Определяет автономный управляемый ресурс для данной сборки. Для управляемого ресурса можно задать атрибуты. |
DefineUnmanagedResource(Byte[]) |
Определяет неуправляемый ресурс для данной сборки как непрозрачный BLOB-объект байтов. |
DefineUnmanagedResource(String) |
Определяет файл неуправляемого ресурса для данной сборки по заданному имени файла ресурсов. |
DefineVersionInfoResource() |
Определяет неуправляемый ресурс сведений о версии с помощью сведений, указанных в объекте AssemblyName и настраиваемых атрибутах сборки. |
DefineVersionInfoResource(String, String, String, String, String) |
Определяет неуправляемую версию информационного ресурса для этой сборки с учетом заданных спецификаций. |
Equals(Object) |
Возвращает значение, указывающее, совпадает ли данный экземпляр с указанным объектом. |
Equals(Object) |
Определяет равенство сборки и заданного объекта. (Унаследовано от Assembly) |
GetCustomAttributes(Boolean) |
Возвращает все настраиваемые атрибуты, которые были применены к текущему AssemblyBuilder. |
GetCustomAttributes(Boolean) |
Получает все настраиваемые атрибуты для этой сборки. (Унаследовано от Assembly) |
GetCustomAttributes(Type, Boolean) |
Возвращает настраиваемые атрибуты, примененные к текущему AssemblyBuilder, которые являются производными от указанного типа атрибута. |
GetCustomAttributes(Type, Boolean) |
Получает настраиваемые атрибуты для этой сборки как заданные по типу. (Унаследовано от Assembly) |
GetCustomAttributesData() |
Возвращает объекты CustomAttributeData, содержащие сведения об атрибутах, которые были применены к текущему AssemblyBuilder. |
GetCustomAttributesData() |
Возвращает сведения об атрибутах, примененных к текущему объекту Assembly; сведения представляют собой объекты CustomAttributeData. (Унаследовано от Assembly) |
GetDynamicModule(String) |
Возвращает динамический модуль с указанным именем. |
GetDynamicModuleCore(String) |
При переопределении в производном классе возвращает динамический модуль с указанным именем. |
GetExportedTypes() |
Возвращает экспортированные типы, определенные в этой сборке. |
GetExportedTypes() |
Получает открытые типы, определенные в этой сборке и видимые за ее пределами. (Унаследовано от Assembly) |
GetFile(String) |
Возвращает объект FileStream для указанного файла из таблицы файлов манифеста данной сборки. |
GetFile(String) |
Возвращает объект FileStream для указанного файла из таблицы файлов манифеста данной сборки. (Унаследовано от Assembly) |
GetFiles() |
Получает файлы в таблице файлов манифеста сборки. (Унаследовано от Assembly) |
GetFiles(Boolean) |
Получает файлы из таблицы манифеста сборки с указанием включать или не включать модули ресурсов. |
GetFiles(Boolean) |
Получает файлы из таблицы манифеста сборки с указанием включать или не включать модули ресурсов. (Унаследовано от Assembly) |
GetForwardedTypes() |
Определяет и представляет динамическую сборку. (Унаследовано от Assembly) |
GetHashCode() |
Возвращает хэш-код данного экземпляра. |
GetHashCode() |
Возвращает хэш-код данного экземпляра. (Унаследовано от Assembly) |
GetLoadedModules() |
Получает все загруженные модули, являющиеся частью этой сборки. (Унаследовано от Assembly) |
GetLoadedModules(Boolean) |
Возвращает все загруженные модули, входящие в эту сборку, и при необходимости включает модули ресурсов. |
GetLoadedModules(Boolean) |
Получает все загруженные модули, входящие в эту сборку, с заданием возможности включения модулей ресурсов. (Унаследовано от Assembly) |
GetManifestResourceInfo(String) |
Возвращает сведения о сохранении заданного ресурса. |
GetManifestResourceNames() |
Загружает указанный ресурс манифеста из сборки. |
GetManifestResourceStream(String) |
Загружает указанный ресурс манифеста из сборки. |
GetManifestResourceStream(Type, String) |
Загружает из сборки указанный ресурс манифеста с учетом ограничения области действия пространства имен по типу. |
GetManifestResourceStream(Type, String) |
Загружает из сборки указанный ресурс манифеста с учетом ограничения области действия пространства имен по типу. (Унаследовано от Assembly) |
GetModule(String) |
Получает указанный модуль этой сборки. |
GetModule(String) |
Получает указанный модуль этой сборки. (Унаследовано от Assembly) |
GetModules() |
Получает все модули, являющиеся частью этой сборки. (Унаследовано от Assembly) |
GetModules(Boolean) |
Получает все модули, входящие в эту сборку, и при необходимости включает модули ресурсов. |
GetModules(Boolean) |
Получает все загруженные модули, входящие в эту сборку, с указанием возможности включения модулей ресурсов. (Унаследовано от Assembly) |
GetName() |
Получает имя AssemblyName для этой сборки. (Унаследовано от Assembly) |
GetName(Boolean) |
Получает имя AssemblyName, которое было указано при создании текущей динамической сборки, и устанавливает базу кода в соответствии с указанием. |
GetName(Boolean) |
Возвращает значение AssemblyName для этой сборки, база кода устанавливается в соответствии с параметром |
GetObjectData(SerializationInfo, StreamingContext) |
Устаревшие..
Получает сведения сериализации со всеми данными, необходимыми для повторного создания экземпляра этой сборки. (Унаследовано от Assembly) |
GetReferencedAssemblies() |
Получает неполный список объектов AssemblyName для сборок, на которые ссылается этот AssemblyBuilder. |
GetReferencedAssemblies() |
Возвращает объекты AssemblyName для всех сборок, на которые ссылается данная сборка. (Унаследовано от Assembly) |
GetSatelliteAssembly(CultureInfo) |
Получает сопутствующую сборку для указанной культуры. |
GetSatelliteAssembly(CultureInfo) |
Получает сопутствующую сборку для указанной культуры. (Унаследовано от Assembly) |
GetSatelliteAssembly(CultureInfo, Version) |
Получает указанную версию вспомогательной сборки для указанной культуры. |
GetSatelliteAssembly(CultureInfo, Version) |
Получает указанную версию вспомогательной сборки для указанной культуры. (Унаследовано от Assembly) |
GetType() |
Определяет и представляет динамическую сборку. (Унаследовано от Assembly) |
GetType(String) |
Возвращает объект Type с указанным именем в экземпляре сборки. (Унаследовано от Assembly) |
GetType(String, Boolean) |
Возвращает объект Type с заданным именем в экземпляре сборки и может вызывать исключение, если тип не найден. (Унаследовано от Assembly) |
GetType(String, Boolean, Boolean) |
Возвращает указанный тип из типов, которые определены и созданы в текущем AssemblyBuilder. |
GetType(String, Boolean, Boolean) |
Возвращает объект Type с заданным именем в экземпляре сборки, с возможностями игнорировать регистр и вызвать исключение, если тип не найден. (Унаследовано от Assembly) |
GetTypes() |
Возвращает все типы, определенные в этой сборке. (Унаследовано от Assembly) |
IsDefined(Type, Boolean) |
Возвращает значение, указывающее, применяется ли к данному члену один или несколько экземпляров определенного типа атрибута. |
IsDefined(Type, Boolean) |
Указывает, применен ли конкретный атрибут к сборке. (Унаследовано от Assembly) |
LoadModule(String, Byte[]) |
Загружает модуль, внутренний для этой сборки, с образом в формате COFF, содержащим включенный модуль или файл ресурсов. (Унаследовано от Assembly) |
LoadModule(String, Byte[], Byte[]) |
Загружает модуль, внутренний для этой сборки, с образом в формате COFF, содержащим включенный модуль или файл ресурсов. Также загружаются необработанные байты, представляющие собой символы для модуля. (Унаследовано от Assembly) |
MemberwiseClone() |
Создает неполную копию текущего объекта Object. (Унаследовано от Object) |
Save(String) |
Сохраняет динамическую сборку на диск. |
Save(String, PortableExecutableKinds, ImageFileMachine) |
Сохраняет эту динамическую сборку на диске, указывая природу кода в исполняемых файлах сборки и целевую платформу. |
SetCustomAttribute(ConstructorInfo, Byte[]) |
Задает настраиваемый атрибут для этой сборки с помощью большого двоичного объекта настраиваемого атрибута. |
SetCustomAttribute(CustomAttributeBuilder) |
Задает настраиваемый атрибут для этой сборки с помощью построителя настраиваемого атрибута. |
SetCustomAttributeCore(ConstructorInfo, ReadOnlySpan<Byte>) |
При переопределении в производном классе задает настраиваемый атрибут для этой сборки. |
SetEntryPoint(MethodInfo) |
Задает точку входа для этой динамической сборки при условии, что выполняется сборка консольного приложения. |
SetEntryPoint(MethodInfo, PEFileKinds) |
Задает точку входа для этой сборки и определяет тип переносимого исполняемого файла (PE-файла), построение которого выполняется. |
ToString() |
Возвращает полное имя сборки, также называемое отображаемым именем. (Унаследовано от Assembly) |
События
ModuleResolve |
Возникает, если загрузчик классов общеязыковой среды выполнения не может обработать ссылку на внутренний модуль сборки, используя обычные средства. (Унаследовано от Assembly) |
Явные реализации интерфейса
_Assembly.GetType() |
Возвращает тип текущего экземпляра. (Унаследовано от Assembly) |
_AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации. |
_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr) |
Возвращает сведения о типе объекта, которые затем могут использоваться для получения сведений о типе интерфейса. |
_AssemblyBuilder.GetTypeInfoCount(UInt32) |
Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1). |
_AssemblyBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Предоставляет доступ к открытым свойствам и методам объекта. |
ICustomAttributeProvider.GetCustomAttributes(Boolean) |
Возвращает массив всех настраиваемых атрибутов, определенных для этого элемента, за исключением именованных атрибутов, или пустой массив, если атрибуты отсутствуют. (Унаследовано от Assembly) |
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) |
Возвращает массив настраиваемых атрибутов, определенных для этого элемента с учетом типа, или пустой массив, если отсутствуют настраиваемые атрибуты определенного типа. (Унаследовано от Assembly) |
ICustomAttributeProvider.IsDefined(Type, Boolean) |
Указывает, сколько экземпляров |
Методы расширения
GetExportedTypes(Assembly) |
Определяет и представляет динамическую сборку. |
GetModules(Assembly) |
Определяет и представляет динамическую сборку. |
GetTypes(Assembly) |
Определяет и представляет динамическую сборку. |
GetCustomAttribute(Assembly, Type) |
Извлекает пользовательский атрибут заданного типа, примененный к указанной сборке. |
GetCustomAttribute<T>(Assembly) |
Извлекает пользовательский атрибут заданного типа, примененный к указанной сборке. |
GetCustomAttributes(Assembly) |
Извлекает коллекцию настраиваемых атрибутов, примененных к указанной сборке. |
GetCustomAttributes(Assembly, Type) |
Извлекает коллекцию пользовательских атрибутов заданного типа, примененных к указанной сборке. |
GetCustomAttributes<T>(Assembly) |
Извлекает коллекцию пользовательских атрибутов заданного типа, примененных к указанной сборке. |
IsDefined(Assembly, Type) |
Указывает, применены ли какие-либо пользовательские атрибуты заданного типа к указанной сборке. |
TryGetRawMetadata(Assembly, Byte*, Int32) |
Извлекает раздел метаданных сборки для использования с MetadataReader. |
Применяется к
См. также раздел
Обратная связь
https://aka.ms/ContentUserFeedback.
Ожидается в ближайшее время: в течение 2024 года мы постепенно откажемся от GitHub Issues как механизма обратной связи для контента и заменим его новой системой обратной связи. Дополнительные сведения см. в разделеОтправить и просмотреть отзыв по