gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:59:20 24 4
gpt4 key购买 nike

这个问题与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"));

关于c# - 如何使用 mono.cecil 添加没有默认构造函数的自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10281104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com