c# – 如何使用mono.cecil在没有默认构造函数的情况下添加自定义属性

此问题与 this one有关,但不重复. Jb在那里发布了要添加自定义属性,以下代码段将起作用:
ModuleDeFinition module = ...;
MethodDeFinition targetmethod = ...;
MethodReference attributeConstructor = module.Import(
    typeof(DebuggerHiddenAttribute).GetConstructor(Type.EmptyTypes));

targetmethod.CustomAttributes.Add(new CustomAttribute(attributeConstructor));
module.Write(...);

我想使用类似的东西,但添加一个自定义属性,其构造函数在其(唯一)构造函数中采用两个字符串参数,并且我想为这些(显然)指定值.有人可以帮忙吗?

解决方法

首先,您必须获得对正确版本的构造函数的引用:
MethodReference attributeConstructor = module.Import(
    typeof(MyAttribute).GetConstructor(new [] { typeof(string),typeof(string) }));

然后,您只需使用字符串参数填充自定义属性

CustomAttribute attribute = new CustomAttribute(attributeConstructor);
attribute.constructorarguments.Add(
        new CustomAttributeArgument(
            module.TypeSystem.String,"Foo"));
attribute.constructorarguments.Add(
        new CustomAttributeArgument(
            module.TypeSystem.String,"Bar"));

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...