动态编译程序集,怎么样获取Attribute

faib920 2013-05-09 02:49:51
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
...全文
11636 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
faib920 2013-05-26
  • 打赏
  • 举报
回复
此问题已经解决
ckyd 2013-05-26
  • 打赏
  • 举报
回复
深深的学习一下!
threenewbee 2013-05-10
  • 打赏
  • 举报
回复
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("dynamic"), AssemblyBuilderAccess.Run); 在此之前,dynamic并没有被正确编译和加载。
faib920 2013-05-10
  • 打赏
  • 举报
回复
但是都能够取出类名的了,如果把 t1.SetCustomAttribute(new CustomAttributeBuilder(con, new[] { t2.UnderlyingSystemType })); 的t2.UnderlyingSystemType 换成 typeof(string) 就没有任何问题了 我的怀疑是,type2和type1同在一个程序集内,不能在特性中引用
faib920 2013-05-10
  • 打赏
  • 举报
回复
但是都能够取出类名的了,如果把 t1.SetCustomAttribute(new CustomAttributeBuilder(con, new[] { t2.UnderlyingSystemType }));
faib920 2013-05-09
  • 打赏
  • 举报
回复
没有帮忙解决?

17,740

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 .NET Framework
社区管理员
  • .NET Framework社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧