public SetCustomAttribute ( System customBuilder ) : void | ||
customBuilder | System | |
return | void |
FieldBuilder myField = myTypeBuilder.DefineField("myField", typeof(int), FieldAttributes.Public); Type[] constructorArgs = new Type[] { typeof(int) }; ConstructorInfo myConstructorInfo = typeof(MyCustomAttribute).GetConstructor(constructorArgs); CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(myConstructorInfo, new object[] { 42 }); myField.SetCustomAttribute(attributeBuilder);
FieldBuilder myField = myTypeBuilder.DefineField("myField", typeof(int), FieldAttributes.Public); Type[] constructorArgs1 = new Type[] { typeof(int) }; ConstructorInfo myConstructorInfo1 = typeof(MyCustomAttribute1).GetConstructor(constructorArgs1); CustomAttributeBuilder attributeBuilder1 = new CustomAttributeBuilder(myConstructorInfo1, new object[] { 42 }); Type[] constructorArgs2 = new Type[] { typeof(string) }; ConstructorInfo myConstructorInfo2 = typeof(MyCustomAttribute2).GetConstructor(constructorArgs2); CustomAttributeBuilder attributeBuilder2 = new CustomAttributeBuilder(myConstructorInfo2, new object[] { "Hello world!" }); myField.SetCustomAttribute(attributeBuilder1); myField.SetCustomAttribute(attributeBuilder2);In this example, we create a dynamic field and set two custom attributes on it. The process is similar to Example 1, but we create two CustomAttributeBuilder objects and call SetCustomAttribute twice to associate both of them with the field. Both of these examples require the System.Reflection.Emit namespace, which is part of the .NET Framework Class Library.