微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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"));

原文地址:https://www.jb51.cc/csharp/97055.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐