加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:49:10 所属栏目:百科 来源:网络整理
导读:此问题与 this one有关,但不重复. Jb在那里发布了要添加自定义属性,以下代码段将起作用: ModuleDefinition module = ...;MethodDefinition targetMethod = ...;MethodReference attributeConstructor = module.Import( typeof(DebuggerHiddenAttribute).Get
此问题与 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"));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读