本文整理汇总了C#中System.Reflection.Emit.TypeBuilder.SetCustomAttribute方法的典型用法代码示例。如果您正苦于以下问题:C# TypeBuilder.SetCustomAttribute方法的具体用法?C# TypeBuilder.SetCustomAttribute怎么用?C# TypeBuilder.SetCustomAttribute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Reflection.Emit.TypeBuilder
的用法示例。
在下文中一共展示了TypeBuilder.SetCustomAttribute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddEntityElementIdAnnotation
private static void AddEntityElementIdAnnotation(TypeBuilder typeBuilder, EntityElement entity)
{
var id = entity.Identity.Id.ToString();
var constructor = typeof(EntityElementIdAttribute).GetConstructors().First();
var customAttributeBuilder = new CustomAttributeBuilder(constructor, new object[] { id });
typeBuilder.SetCustomAttribute(customAttributeBuilder);
}
示例2: AddAttribute
private void AddAttribute(TypeBuilder typeBuilder, Type attrType, Type[] attrCtorParamTypes, object[] attrCtorParams)
{
var ctorInfo = attrType.GetConstructor(attrCtorParamTypes);
if (ctorInfo != null)
{
var attrBuilder = new CustomAttributeBuilder(ctorInfo, attrCtorParams);
typeBuilder.SetCustomAttribute(attrBuilder);
}
}
示例3: ProcessEntityComponent
private static void ProcessEntityComponent(Type baseType, TypeBuilder typeBuilder)
{
if (typeof(EntityComponent).IsAssignableFrom(baseType))
{
// Add AllowMultipleComponentsAttribute on EntityComponent yaml proxy (since there might be more than one)
var allowMultipleComponentsAttributeCtor = typeof(AllowMultipleComponentsAttribute).GetConstructor(Type.EmptyTypes);
var allowMultipleComponentsAttribute = new CustomAttributeBuilder(allowMultipleComponentsAttributeCtor, new object[0]);
typeBuilder.SetCustomAttribute(allowMultipleComponentsAttribute);
}
}
示例4: SetHiddenAttribute
internal static void SetHiddenAttribute(TypeBuilder tb)
{
if (s_HiddenCABuilder == null)
{
// Hide the type from Object Browsers
Type []aConsParams = new Type[1];
aConsParams[0] = typeof(TypeLibTypeFlags);
ConstructorInfo Cons = typeof(TypeLibTypeAttribute).GetConstructor(aConsParams);
Object []aArgs = new Object[1];
aArgs[0] = TypeLibTypeFlags.FHidden;
s_HiddenCABuilder = new CustomAttributeBuilder(Cons, aArgs);
}
tb.SetCustomAttribute(s_HiddenCABuilder);
}
示例5: Implement
internal void Implement(TypeBuilder typeBuilder)
{
if (_dataContract != null)
{
// Use base data contract properties to help determine values of properties the proxy type's data contract.
var propertyValues = new object[]
{
// IsReference
_dataContract.IsReference
};
var attributeBuilder = new CustomAttributeBuilder(
_dataContractAttributeConstructor, new object[0], _dataContractProperties, propertyValues);
typeBuilder.SetCustomAttribute(attributeBuilder);
}
}
示例6: SetClassInterfaceTypeToNone
internal static void SetClassInterfaceTypeToNone(TypeBuilder tb)
{
// Create the ClassInterface(ClassInterfaceType.None) CA builder if we haven't created it yet.
if (s_NoClassItfCABuilder == null)
{
Type []aConsParams = new Type[1];
aConsParams[0] = typeof(ClassInterfaceType);
ConstructorInfo Cons = typeof(ClassInterfaceAttribute).GetConstructor(aConsParams);
Object[] aArgs = new Object[1];
aArgs[0] = ClassInterfaceType.None;
s_NoClassItfCABuilder = new CustomAttributeBuilder(Cons, aArgs);
}
// Set the class interface type to none.
tb.SetCustomAttribute(s_NoClassItfCABuilder);
}
示例7: Invoke
public static void Invoke(TypeBuilder t, string ExternalTarget)
{
t.SetCustomAttribute(
new CustomAttributeBuilder(
typeof(ScriptAttribute).GetConstructor(new Type[0]),
new object[0],
namedProperties: new[] { typeof(ScriptAttribute).GetProperty("HasNoPrototype") },
propertyValues: new object[] { true },
namedFields: new[] { typeof(ScriptAttribute).GetField("ExternalTarget") },
fieldValues: new object[] { ExternalTarget }
)
);
}
示例8: SetCustomAttributes
public static void SetCustomAttributes(TypeBuilder tb, IPersistentMap attributes)
{
for (ISeq s = RT.seq(attributes); s != null; s = s.next())
tb.SetCustomAttribute(CreateCustomAttributeBuilder((IMapEntry)(s.first())));
}
示例9: AddSerializationSupport
private static void AddSerializationSupport(System.Type baseType, System.Type[] baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField, ConstructorBuilder defaultConstructor)
{
ConstructorInfo serializableConstructor = typeof(SerializableAttribute).GetConstructor(new System.Type[0]);
var customAttributeBuilder = new CustomAttributeBuilder(serializableConstructor, new object[0]);
typeBuilder.SetCustomAttribute(customAttributeBuilder);
DefineSerializationConstructor(typeBuilder, interceptorField, defaultConstructor);
ImplementGetObjectData(baseType, baseInterfaces, typeBuilder, interceptorField);
}
示例10: Seal
internal override void Seal(TypeDescription existing = null)
{
if (PocoType != null || TypeBuilder != null) return;
var name = "POCO" + Guid.NewGuid().ToString().Replace("-", "");
var protoMemberAttr = typeof(ProtoMemberAttribute).GetConstructor(new[] { typeof(int) });
var protoContractAttr = typeof(ProtoContractAttribute).GetConstructor(new Type[0]);
var fields = new Dictionary<string, FieldInfo>();
TypeBuilder = ModuleBuilder.DefineType(name, TypeAttributes.Public, typeof(DynamicObject), new [] { typeof(IEnumerable) });
var ix = 1;
foreach (var kv in Members.OrderBy(o => o.Key, StringComparer.Ordinal))
{
var memberAttrBuilder = new CustomAttributeBuilder(protoMemberAttr, new object[] { ix });
kv.Value.Seal(existing);
var propType = kv.Value.GetPocoType(existing);
var field = TypeBuilder.DefineField(kv.Key, propType, FieldAttributes.Public);
field.SetCustomAttribute(memberAttrBuilder);
fields[kv.Key] = field;
ix++;
}
var contractAttrBuilder = new CustomAttributeBuilder(protoContractAttr, new object[0]);
TypeBuilder.SetCustomAttribute(contractAttrBuilder);
// Define indexer
var strEq = typeof(object).GetMethod("Equals", new[] { typeof(object) });
var tryGetIndexEmit = Sigil.Emit<TryGetIndexerDelegate>.BuildMethod(TypeBuilder, "TryGetIndex", MethodAttributes.Public | MethodAttributes.Virtual, CallingConventions.Standard | CallingConventions.HasThis);
tryGetIndexEmit.LoadArgument(2); // object[]
var invalid = tryGetIndexEmit.DefineLabel("invalid");
tryGetIndexEmit
.Duplicate() // object[] object[]
.LoadLength<object>() // int object[]
.LoadConstant(1); // int int object[]
tryGetIndexEmit.UnsignedBranchIfNotEqual(invalid); // object[]
tryGetIndexEmit
.LoadConstant(0) // int object[]
.LoadElement<object>() // object
.IsInstance<string>(); // int
var valid = tryGetIndexEmit.DefineLabel("valid");
tryGetIndexEmit
.BranchIfTrue(valid) // --empty--
.LoadArgument(2); // object[]
tryGetIndexEmit.MarkLabel(invalid);
tryGetIndexEmit.Pop(); // --empty--
tryGetIndexEmit
.LoadArgument(3) // object&
.LoadNull() // null object&
.StoreIndirect(typeof(object)); // --empty--
tryGetIndexEmit
.LoadConstant(0) // int
.Return(); // --empty--
tryGetIndexEmit.MarkLabel(valid);
tryGetIndexEmit.LoadArgument(3); // object&
tryGetIndexEmit
.LoadArgument(2) // object[] object&
.LoadConstant(0) // int object[] object&
.LoadElement<object>(); // object object&
Sigil.Label next;
var done = tryGetIndexEmit.DefineLabel("done");
foreach (var mem in Members)
{
next = tryGetIndexEmit.DefineLabel("next_" + mem.Key);
var memKey = mem.Key;
var field = fields[memKey];
tryGetIndexEmit
.Duplicate() // object object object&
.LoadConstant(memKey); // string object object object&
tryGetIndexEmit.CallVirtual(strEq); // int object object7&
tryGetIndexEmit.BranchIfFalse(next); // object object&
tryGetIndexEmit
.Pop() // object&
.LoadArgument(0) // this object&
.LoadField(field); // fieldType object&
if (field.FieldType.IsValueType)
{
//.........这里部分代码省略.........
示例11: ApplyTypeAttributes
/// <summary>
/// Applies attributes to the proxy class.
/// </summary>
/// <param name="typeBuilder">The type builder to use.</param>
/// <param name="targetType">The proxied class.</param>
/// <see cref="IProxyTypeBuilder.ProxyTargetAttributes"/>
/// <see cref="IProxyTypeBuilder.TypeAttributes"/>
protected virtual void ApplyTypeAttributes(TypeBuilder typeBuilder, Type targetType)
{
foreach (object attr in GetTypeAttributes(targetType))
{
if (attr is CustomAttributeBuilder)
{
typeBuilder.SetCustomAttribute((CustomAttributeBuilder)attr);
}
else if (attr is CustomAttributeData)
{
typeBuilder.SetCustomAttribute(
ReflectionUtils.CreateCustomAttribute((CustomAttributeData)attr));
}
else if (attr is Attribute)
{
typeBuilder.SetCustomAttribute(ReflectionUtils.CreateCustomAttribute((Attribute)attr));
}
}
}
示例12: Implement
internal void Implement(TypeBuilder typeBuilder, Action<FieldBuilder, bool> registerField)
{
if (_dataContract != null)
{
// Use base data contract properties to help determine values of properties the proxy type's data contract.
object[] propertyValues = new object[] {
// IsReference
_dataContract.IsReference
};
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(s_DataContractAttributeConstructor, new object[0], s_DataContractProperties, propertyValues);
typeBuilder.SetCustomAttribute(attributeBuilder);
}
}
示例13: add_possible_type_attribute
private void add_possible_type_attribute(TypeBuilder tb, ITypeNode type)
{
if (comp_opt.target != TargetType.Dll)
return;
if (type.type_special_kind == type_special_kind.typed_file)
{
Type elem_type = helper.GetTypeReference(type.element_type).tp;
CustomAttributeBuilder cust_bldr = null;
if (type.element_type is ICompiledTypeNode || type.element_type is IRefTypeNode && (type.element_type as IRefTypeNode).pointed_type is ICompiledTypeNode)
cust_bldr = new CustomAttributeBuilder(this.FileOfAttributeConstructor, new object[1] { elem_type });
else
cust_bldr = new CustomAttributeBuilder(this.FileOfAttributeConstructor, new object[1] { elem_type.FullName });
tb.SetCustomAttribute(cust_bldr);
}
else if (type.type_special_kind == type_special_kind.set_type)
{
Type elem_type = helper.GetTypeReference(type.element_type).tp;
CustomAttributeBuilder cust_bldr = null;
if (type.element_type is ICompiledTypeNode || type.element_type is IRefTypeNode && (type.element_type as IRefTypeNode).pointed_type is ICompiledTypeNode)
cust_bldr = new CustomAttributeBuilder(this.SetOfAttributeConstructor, new object[1] { elem_type });
else
cust_bldr = new CustomAttributeBuilder(this.SetOfAttributeConstructor, new object[1] { elem_type.FullName });
tb.SetCustomAttribute(cust_bldr);
}
else if (type.type_special_kind == type_special_kind.short_string)
{
int len = (type as IShortStringTypeNode).Length;
CustomAttributeBuilder cust_bldr = new CustomAttributeBuilder(this.ShortStringAttributeConstructor, new object[1] { len });
tb.SetCustomAttribute(cust_bldr);
}
}
示例14: ConvertFromTree
//Метод, переводящий семантическое дерево в сборку .NET
public void ConvertFromTree(SemanticTree.IProgramNode p, string TargetFileName, string SourceFileName, CompilerOptions options, string[] ResourceFiles)
{
//SystemLibrary.SystemLibInitializer.RestoreStandardFunctions();
bool RunOnly = false;
string fname = TargetFileName;
comp_opt = options;
ad = Thread.GetDomain(); //получаем домен приложения
//ad = ad.DomainManager.CreateDomain("D1", null, null);
an = new AssemblyName(); //создаем имя сборки
an.Version = new Version("1.0.0.0");
string dir = Directory.GetCurrentDirectory();
string source_name = fname;//p.Location.document.file_name;
int pos = source_name.LastIndexOf(Path.DirectorySeparatorChar);
if (pos != -1) //если имя файла указано с путем, то выделяем
{
dir = source_name.Substring(0, pos + 1);
an.CodeBase = String.Concat("file:///", source_name.Substring(0, pos));
source_name = source_name.Substring(pos + 1);
}
string name = source_name.Substring(0, source_name.LastIndexOf('.'));
if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe)
an.Name = name;// + ".exe";
else an.Name = name; //+ ".dll";
if (name == "PABCRtl" || name == "PABCRtl32")
{
an.Flags = AssemblyNameFlags.PublicKey;
an.VersionCompatibility = System.Configuration.Assemblies.AssemblyVersionCompatibility.SameProcess;
an.HashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm.None;
FileStream publicKeyStream = File.Open(Path.Combine(Path.GetDirectoryName(TargetFileName), name == "PABCRtl" ? "PublicKey.snk" : "PublicKey32.snk"), FileMode.Open);
byte[] publicKey = new byte[publicKeyStream.Length];
publicKeyStream.Read(publicKey, 0, (int)publicKeyStream.Length);
// Provide the assembly with a public key.
an.SetPublicKey(publicKey);
publicKeyStream.Close();
}
if (RunOnly)
ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run, dir);//определяем сборку
else
ab = ad.DefineDynamicAssembly(an, AssemblyBuilderAccess.Save, dir);//определяем сборку
//int nn = ad.GetAssemblies().Length;
if (options.NeedDefineVersionInfo)
{
ab.DefineVersionInfoResource(options.Product, options.ProductVersion, options.Company,
options.Copyright, options.TradeMark);
}
if (options.MainResourceFileName != null)
{
try
{
ab.DefineUnmanagedResource(options.MainResourceFileName);
}
catch
{
throw new TreeConverter.SourceFileError(options.MainResourceFileName);
}
}
else if (options.MainResourceData != null)
{
try
{
ab.DefineUnmanagedResource(options.MainResourceData);
}
catch
{
throw new TreeConverter.SourceFileError("");
}
}
save_debug_info = comp_opt.dbg_attrs == DebugAttributes.Debug || comp_opt.dbg_attrs == DebugAttributes.ForDebbuging;
add_special_debug_variables = comp_opt.dbg_attrs == DebugAttributes.ForDebbuging;
//bool emit_sym = true;
if (save_debug_info) //если модуль отладочный, то устанавливаем атрибут, запрещающий inline методов
ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x01, 0x01, 0x00, 0x00 });
//ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00 });
//else
// ab.SetCustomAttribute(typeof(System.Diagnostics.DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new byte[] { 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 });
if (RunOnly)
mb = ab.DefineDynamicModule(name, save_debug_info);
else
{
if (comp_opt.target == TargetType.Exe || comp_opt.target == TargetType.WinExe)
mb = ab.DefineDynamicModule(name + ".exe", an.Name + ".exe", save_debug_info); //определяем модуль (save_debug_info - флаг включать отладочную информацию)
else
mb = ab.DefineDynamicModule(name + ".dll", an.Name + ".dll", save_debug_info);
}
cur_unit = Path.GetFileNameWithoutExtension(SourceFileName);
string entry_cur_unit = cur_unit;
entry_type = mb.DefineType(cur_unit + ".Program", TypeAttributes.Public);//определяем синтетический статический класс основной программы
cur_type = entry_type;
//точка входа в приложение
if (p.main_function != null)
{
ConvertFunctionHeader(p.main_function);
entry_meth = helper.GetMethod(p.main_function).mi as MethodBuilder;
/*entry_meth = entry_type.DefineMethod(p.main_function.name, MethodAttributes.Public | MethodAttributes.Static, typeof(void), GetParamTypes(p.main_function));
for (int i = 0; i < p.main_function.parameters.Length; i++)
//.........这里部分代码省略.........
示例15: Define
public static void Define(TypeBuilder typeB, Interface iface)
{
foreach (Method declMethod in iface.Methods)
DefineMethod (typeB, declMethod.Name, ifaceMethAttr, declMethod.Arguments, false);
if (iface.Properties != null)
foreach (NDesk.DBus.Introspection.Property prop in iface.Properties) {
Type propType = new Signature (prop.Type).ToType ();
PropertyBuilder prop_builder = typeB.DefineProperty (prop.Name, PropertyAttributes.None, propType, Type.EmptyTypes);
if (prop.Access == propertyAccess.read || prop.Access == propertyAccess.readwrite)
prop_builder.SetGetMethod (typeB.DefineMethod ("get_" + prop.Name, ifaceMethAttr | MethodAttributes.SpecialName, propType, Type.EmptyTypes));
if (prop.Access == propertyAccess.write || prop.Access == propertyAccess.readwrite)
prop_builder.SetSetMethod (typeB.DefineMethod ("set_" + prop.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {propType}));
}
if (iface.Signals != null)
foreach (NDesk.DBus.Introspection.Signal signal in iface.Signals) {
Type eventType = DefineHandler (modBdef, signal);
EventBuilder event_builder = typeB.DefineEvent (signal.Name, EventAttributes.None, eventType);
event_builder.SetAddOnMethod (typeB.DefineMethod ("add_" + signal.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {eventType}));
event_builder.SetRemoveOnMethod (typeB.DefineMethod ("remove_" + signal.Name, ifaceMethAttr | MethodAttributes.SpecialName, null, new Type[] {eventType}));
}
//apply InterfaceAttribute
ConstructorInfo interfaceAttributeCtor = typeof (InterfaceAttribute).GetConstructor(new Type[] {typeof (string)});
CustomAttributeBuilder cab = new CustomAttributeBuilder (interfaceAttributeCtor, new object[] {iface.Name});
typeB.SetCustomAttribute (cab);
}