动态编译程序集,怎么样获取Attribute
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("dynamic"), AssemblyBuilderAccess.Run);var module = assembly.DefineDynamicModule("Main");
var t1 = module.DefineType("t1", TypeAttributes.Class | TypeAttributes.Public);
var t2 = module.DefineType("t2", TypeAttributes.Class | TypeAttributes.Public);
var con = typeof(MetadataTypeAttribute).GetConstructor(new [] { typeof(Type) });
var type1 = t1.CreateType();
var type2 = t2.CreateType();
t1.SetCustomAttribute(new CustomAttributeBuilder(con, new[] { t2.UnderlyingSystemType }));
Console.WriteLine(type1);
Console.WriteLine(type2);
Console.WriteLine(assembly.GetReferencedAssemblies());
Console.WriteLine(type1.GetCustomAttributes<MetadataTypeAttribute>());
最后一句报
System.IO.FileNotFoundException : 未能加载文件或程序集“dynamic, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项。系统找不到指定的文件。
在 System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs)
在 System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, IRuntimeMethodInfo ctor, ref IntPtr blob, IntPtr blobEnd, ref Int32 namedArgs)
在 System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
在 System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
在 System.RuntimeType.GetCustomAttributes(Type attributeType, Boolean inherit)
在 Fireasy.Common.Extensions.ReflectionExtension.GetCustomAttributes(ICustomAttributeProvider provider, Boolean inherit) 位置 ReflectionExtension.cs: line 70
在 Fireasy.Data.Test.Entity.EntityBuilderTests.Test2() 位置 EntityBuilderTests.cs: line 98 --------------------编程问答-------------------- 没有帮忙解决? --------------------编程问答-------------------- var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("dynamic"), AssemblyBuilderAccess.Run);
在此之前,dynamic并没有被正确编译和加载。 --------------------编程问答-------------------- 但是都能够取出类名的了,如果把
t1.SetCustomAttribute(new CustomAttributeBuilder(con, new[] { t2.UnderlyingSystemType }));
--------------------编程问答-------------------- 但是都能够取出类名的了,如果把
t1.SetCustomAttribute(new CustomAttributeBuilder(con, new[] { t2.UnderlyingSystemType }));
的t2.UnderlyingSystemType 换成 typeof(string) 就没有任何问题了
我的怀疑是,type2和type1同在一个程序集内,不能在特性中引用 --------------------编程问答-------------------- 此问题已经解决 --------------------编程问答-------------------- 深深的学习一下!
补充:.NET技术 , .NET Framework