[英]Can I apply an attribute to all members of a namespace?
我需要将某个属性(与混淆相关)应用于某个命名空间中的所有类。 我目前正在浏览列表并手动进行操作,但是我希望以自动应用的方式进行操作。 这将为我节省一些工作,但也将确保将来添加到此命名空间的类也具有该属性。
C#在这些方面是否有规定?
我不知道.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);
}
这是一个示例注入器程序:( 注意:我从注入器程序中引用了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)");
}
您可以通过PM> Install-Package Mono.Cecil
Nuget命令PM> Install-Package Mono.Cecil
Mono.Cecil。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.