使用 Cecil 在程序集中添加全局自定义属性

Adding a global custom attribute in the assembly with Cecil

我有这个属性class:

[AttributeUsage(AttributeTargets.Assembly)]
public class PostProcessedAssemblyAttribute : Attribute
{
}

然后写了这段代码:

var moduleG = assembly.MainModule;

            var attributeConstructor =
                    moduleG.ImportReference(
                        typeof(PostProcessedAssemblyAttribute).GetConstructor(Type.EmptyTypes));
            var attribute = new CustomAttribute(attributeConstructor);
            assembly.CustomAttributes.Add(attribute);

 assembly.Write(assemblyPath, writerParameters);

如果我回读程序集,我希望该属性存在,但实际上没有。

我不是 100% 确定我在做什么,所以我肯定做错了什么(例如我不确定从主模块导入属性是否正确),你能指出问题所在吗是?

我需要这个来将程序集标记为已处理。

该代码确实有效,我错误地仅使用 assembly.CustomAttributes.Contains 查找属性,这根本不起作用。最终我解决了它从实际类型创建一个 TypeReference 并根据我需要检查的 TypeReference 的全名检查 CustomAttribute.AttributeType.FullName。