AssemblyBuilder.SetCustomAttribute Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Задает настраиваемый атрибут для этой сборки.
Перегрузки
| Имя | Описание |
|---|---|
| SetCustomAttribute(CustomAttributeBuilder) |
Задайте настраиваемый атрибут для этой сборки с помощью пользовательского построителя атрибутов. |
| SetCustomAttribute(ConstructorInfo, Byte[]) |
Задайте настраиваемый атрибут для этой сборки с помощью указанного пользовательского blob-объекта атрибута. |
SetCustomAttribute(CustomAttributeBuilder)
- Исходный код:
- AssemblyBuilder.cs
- Исходный код:
- AssemblyBuilder.cs
- Исходный код:
- AssemblyBuilder.cs
- Исходный код:
- AssemblyBuilder.cs
- Исходный код:
- AssemblyBuilder.cs
Задайте настраиваемый атрибут для этой сборки с помощью пользовательского построителя атрибутов.
public:
void SetCustomAttribute(System::Reflection::Emit::CustomAttributeBuilder ^ customBuilder);
public void SetCustomAttribute(System.Reflection.Emit.CustomAttributeBuilder customBuilder);
member this.SetCustomAttribute : System.Reflection.Emit.CustomAttributeBuilder -> unit
Public Sub SetCustomAttribute (customBuilder As CustomAttributeBuilder)
Параметры
- customBuilder
- CustomAttributeBuilder
Экземпляр вспомогательного класса для определения пользовательского атрибута.
Исключения
customBuilder равно null.
Вызывающий объект не имеет требуемого разрешения.
Примеры
В следующем примере кода показано использование SetCustomAttribute внутри AssemblyBuilderс помощью CustomAttributeBuilder.
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class MyAttribute : Attribute
{
public String s;
public int x;
public MyAttribute(String s, int x)
{
this.s = s;
this.x = x;
}
}
class MyApplication
{
public static void Main()
{
Type customAttribute = CreateCallee(Thread.GetDomain());
object[] attributes = customAttribute.Assembly.GetCustomAttributes(true);
Console.WriteLine("MyAttribute custom attribute contains : ");
for(int index=0; index < attributes.Length; index++)
{
if(attributes[index] is MyAttribute)
{
Console.WriteLine("s : " + ((MyAttribute)attributes[index]).s);
Console.WriteLine("x : " + ((MyAttribute)attributes[index]).x);
break;
}
}
}
private static Type CreateCallee(AppDomain domain)
{
AssemblyName myAssemblyName = new AssemblyName();
myAssemblyName.Name = "EmittedAssembly";
AssemblyBuilder myAssembly = domain.DefineDynamicAssembly(myAssemblyName,
AssemblyBuilderAccess.Run);
Type myType = typeof(MyAttribute);
ConstructorInfo infoConstructor = myType.GetConstructor(new Type[2]{typeof(String), typeof(int)});
CustomAttributeBuilder attributeBuilder =
new CustomAttributeBuilder(infoConstructor, new object[2]{"Hello", 2});
myAssembly.SetCustomAttribute(attributeBuilder);
ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");
// Define a public class named "HelloWorld" in the assembly.
TypeBuilder helloWorldClass = myModule.DefineType("HelloWorld", TypeAttributes.Public);
return(helloWorldClass.CreateType());
}
}
<AttributeUsage(AttributeTargets.All, AllowMultiple := False)> _
Public Class MyAttribute
Inherits Attribute
Public s As String
Public x As Integer
Public Sub New(s As String, x As Integer)
Me.s = s
Me.x = x
End Sub
End Class
Class MyApplication
Public Shared Sub Main()
Dim customAttribute As Type = CreateCallee(Thread.GetDomain())
Dim attributes As Object() = customAttribute.Assembly.GetCustomAttributes(True)
Console.WriteLine("MyAttribute custom attribute contains : ")
Dim index As Integer
For index = 0 To attributes.Length - 1
If TypeOf attributes(index) Is MyAttribute Then
Console.WriteLine("s : " + CType(attributes(index), MyAttribute).s)
Console.WriteLine("x : " + CType(attributes(index), MyAttribute).x.ToString())
Exit For
End If
Next index
End Sub
Private Shared Function CreateCallee(domain As AppDomain) As Type
Dim myAssemblyName As New AssemblyName()
myAssemblyName.Name = "EmittedAssembly"
Dim myAssembly As AssemblyBuilder = _
domain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run)
Dim myType As Type = GetType(MyAttribute)
Dim infoConstructor As ConstructorInfo = _
myType.GetConstructor(New Type(1) {GetType(String), GetType(Integer)})
Dim attributeBuilder As New CustomAttributeBuilder(infoConstructor, New Object(1) {"Hello", 2})
myAssembly.SetCustomAttribute(attributeBuilder)
Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule")
' Define a public class named "HelloWorld" in the assembly.
Dim helloWorldClass As TypeBuilder = myModule.DefineType("HelloWorld", TypeAttributes.Public)
Return helloWorldClass.CreateType()
End Function 'CreateCallee
End Class
Комментарии
Note
SetCustomAttribute нельзя использовать для задания декларативных атрибутов безопасности. Используйте одну из перегрузок DefineDynamicAssembly , которые принимают необходимые, необязательные и отклоненные разрешения.
Применяется к
SetCustomAttribute(ConstructorInfo, Byte[])
- Исходный код:
- AssemblyBuilder.cs
- Исходный код:
- AssemblyBuilder.cs
- Исходный код:
- AssemblyBuilder.cs
- Исходный код:
- AssemblyBuilder.cs
- Исходный код:
- AssemblyBuilder.cs
Задайте настраиваемый атрибут для этой сборки с помощью указанного пользовательского blob-объекта атрибута.
public:
void SetCustomAttribute(System::Reflection::ConstructorInfo ^ con, cli::array <System::Byte> ^ binaryAttribute);
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute);
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute);
member this.SetCustomAttribute : System.Reflection.ConstructorInfo * byte[] -> unit
[<System.Runtime.InteropServices.ComVisible(true)>]
member this.SetCustomAttribute : System.Reflection.ConstructorInfo * byte[] -> unit
Public Sub SetCustomAttribute (con As ConstructorInfo, binaryAttribute As Byte())
Параметры
- con
- ConstructorInfo
Конструктор для пользовательского атрибута.
- binaryAttribute
- Byte[]
Байтовый большой двоичный объект, представляющий атрибуты.
- Атрибуты
Исключения
con или binaryAttribute есть null.
Вызывающий объект не имеет требуемого разрешения.
con не RuntimeConstructorInfo является объектом.
Примеры
В следующем примере кода показано использование SetCustomAttribute пользовательского атрибута к динамической сборке.
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class MyAttribute : Attribute
{
public bool s;
public MyAttribute(bool s)
{
this.s = s;
}
}
class MyApplication
{
public static void Main()
{
Type customAttribute = CreateCallee(Thread.GetDomain());
object[] attributes = customAttribute.Assembly.GetCustomAttributes(true);
Console.WriteLine("MyAttribute custom attribute contains : ");
for(int index=0; index < attributes.Length; index++)
{
if(attributes[index] is MyAttribute)
{
Console.WriteLine("s : " + ((MyAttribute)attributes[index]).s);
break;
}
}
}
private static Type CreateCallee(AppDomain domain)
{
AssemblyName myAssemblyName = new AssemblyName();
myAssemblyName.Name = "EmittedAssembly";
AssemblyBuilder myAssembly = domain.DefineDynamicAssembly(myAssemblyName,
AssemblyBuilderAccess.Run);
Type myType = typeof(MyAttribute);
ConstructorInfo infoConstructor = myType.GetConstructor(new Type[]{typeof(bool)});
myAssembly.SetCustomAttribute(infoConstructor, new byte[]{01,00,01});
ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");
// Define a public class named "HelloWorld" in the assembly.
TypeBuilder helloWorldClass = myModule.DefineType("HelloWorld", TypeAttributes.Public);
return(helloWorldClass.CreateType());
}
}
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
<AttributeUsage(AttributeTargets.All, AllowMultiple := False)> _
Public Class MyAttribute
Inherits Attribute
Public s As Boolean
Public Sub New(s As Boolean)
Me.s = s
End Sub
End Class
Class MyApplication
Public Shared Sub Main()
Dim customAttribute As Type = CreateCallee(Thread.GetDomain())
Dim attributes As Object() = customAttribute.Assembly.GetCustomAttributes(True)
Console.WriteLine("MyAttribute custom attribute contains : ")
Dim index As Integer
For index = 0 To attributes.Length - 1
If TypeOf attributes(index) Is MyAttribute Then
Console.WriteLine("s : " + CType(attributes(index), MyAttribute).s.ToString())
Exit For
End If
Next index
End Sub
Private Shared Function CreateCallee(domain As AppDomain) As Type
Dim myAssemblyName As New AssemblyName()
myAssemblyName.Name = "EmittedAssembly"
Dim myAssembly As AssemblyBuilder = domain.DefineDynamicAssembly(myAssemblyName, _
AssemblyBuilderAccess.Run)
Dim myType As Type = GetType(MyAttribute)
Dim infoConstructor As ConstructorInfo = myType.GetConstructor(New Type() {GetType(Boolean)})
myAssembly.SetCustomAttribute(infoConstructor, New Byte() {01, 00, 01})
Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule")
' Define a public class named "HelloWorld" in the assembly.
Dim helloWorldClass As TypeBuilder = myModule.DefineType("HelloWorld", TypeAttributes.Public)
Return helloWorldClass.CreateType()
End Function 'CreateCallee
End Class
Комментарии
Сведения о форматировании binaryAttributeсм. в спецификации метаданных в разделе II спецификации CLR.
RuntimeConstructorInfo — это специальный тип, созданный системой. Он является производным от ConstructorInfo класса, и любой ConstructorInfo объект, полученный посредством отражения, фактически является экземпляром RuntimeConstructorInfo.
Note
SetCustomAttribute нельзя использовать для задания декларативных атрибутов безопасности. Используйте одну из перегрузок DefineDynamicAssembly , которые принимают необходимые, необязательные и отклоненные разрешения.