简体   繁体   English

我可以将属性应用于名称空间的所有成员吗?

[英]Can I apply an attribute to all members of a namespace?

I need to apply an attribute (obfuscation related) to all classes in a certain namespace. 我需要将某个属性(与混淆相关)应用于某个命名空间中的所有类。 I'm currently working through the list and doing it by hand, but I'd prefer to do it in a way that it is applied automatically. 我目前正在浏览列表并手动进行操作,但是我希望以自动应用的方式进行操作。 This would save me some work, but also would ensure that classes added to this namespace in the future will have the attribute as well. 这将为我节省一些工作,但也将确保将来添加到此命名空间的类也具有该属性。

Does C# have any provisions along these lines? C#在这些方面是否有规定?

I'm not aware of any built-in facility in .Net that can do it, but you can write one yourself easily using Mono.Cecil here is a method which can inject specified attribute in designated types. 我不知道.Net中有任何内置功能可以做到这一点,但是您可以使用Mono.Cecil轻松编写自己的Mono.Cecil是一种可以将指定属性注入指定类型的方法。

    private static void InjectAttribute<T>(string source,string destination,string nameSpace="")where T:Attribute
    {
        var assembly = AssemblyDefinition.ReadAssembly(source);
        var module = assembly.MainModule;
        var types = module.GetTypes();


        var attributeConstructor = module.Import(typeof (T).GetConstructor(Type.EmptyTypes));

        foreach (var type in types)
        {
            if (type.FullName.StartsWith(nameSpace))
                type.CustomAttributes.Add(new CustomAttribute(attributeConstructor));
        }

        assembly.Write(destination);
    }

and here is a sample Injector Program: (NOTE: I referenced Obfuscate library from my injector program so there is no need to resolve the type for Cecil) : 这是一个示例注入器程序:( 注意:我从注入器程序中引用了Obfuscate库,因此无需解析Cecil的类型)

    private static void Main(string[] args)
    {
        //NOTE:obfuscatelib is already referenced to injector so no need to resolve types
        InjectAttribute<ObfuscationLib.ObfuscateAttribute>(@"assembly path",
            @"injected assembly path","namespace (based on full name)");
    }

you can obtain Mono.Cecil through PM> Install-Package Mono.Cecil Nuget command. 您可以通过PM> Install-Package Mono.Cecil Nuget命令PM> Install-Package Mono.Cecil Mono.Cecil。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM