[英]Replace Attribute constructor arguments with mono.cecil or postsharp
我有一個示例方法定義:
[FooAttribute("One","time")]
public void Bar(){}
是否可以通過上述技術之一來改變,例如,論證“一”到“二”?
假設以下屬性和類:
public class MyAttribute : Attribute
{
public MyAttribute(string a, string b)
{
this.a = a;
this.b = b;
}
private string a,b;
}
[My("foo", "bar")]
class WithAttribute
{
}
您可以使用類似於以下內容的一些代碼(請記住,此代碼僅用於演示目的,並且它假定了許多內容並且根本不執行任何錯誤處理)
var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
var type = assembly.MainModule.Types.Where(t => t.Name.Contains("WithAttribute")).Single();
var attr = type.CustomAttributes.Where(ca => ca.AttributeType.FullName.Contains("MyAttribute")).Single();
type.CustomAttributes.Remove(attr);
var newAttr = new CustomAttribute(attr.Constructor)
{
ConstructorArguments =
{
new CustomAttributeArgument(
attr.ConstructorArguments[0].Type,
attr.ConstructorArguments[0].Value + "-Appended"),
new CustomAttributeArgument(
attr.ConstructorArguments[1].Type,
attr.ConstructorArguments[1].Value)
}
};
type.CustomAttributes.Add(newAttr);
assembly.Write(path);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.