[英]Get a method with a single or no attributes with Reflection in C#
[英]How to get all attributes and attributes data of a method using reflection in C#
最終目標是將“按原樣”的屬性從方法復制到生成的類中的另一個方法。
public class MyOriginalClass
{
[Attribute1]
[Attribute2("value of attribute 2")]
void MyMethod(){}
}
public class MyGeneratedClass
{
[Attribute1]
[Attribute2("value of attribute 2")]
void MyGeneratedMethod(){}
}
我能夠使用MethodInfo.GetCustomAttributes()
列出方法的屬性,但是,這不會給我屬性參數; 我需要在生成的類上生成相應的屬性。
請注意,我不知道屬性的類型(不能轉換屬性)。
我正在使用CodeDom生成代碼。
MethodInfo.GetCustomAttributesData()具有所需的信息:
// method is the MethodInfo reference
// member is CodeMemberMethod (CodeDom) used to generate the output method;
foreach (CustomAttributeData attributeData in method.GetCustomAttributesData())
{
var arguments = new List<CodeAttributeArgument>();
foreach (var argument in attributeData.ConstructorArguments)
{
arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(argument.ToString())));
}
if (attributeData.NamedArguments != null)
foreach (var argument in attributeData.NamedArguments)
{
arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(argument.ToString())));
}
member.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(attributeData.AttributeType), arguments.ToArray()));
}
我不知道怎么可能這樣做。 GetCustomAttributes返回一個對象數組,每個對象都是一個自定義屬性的實例。 無法知道使用哪個構造函數來創建該實例,因此無法知道如何為這樣的構造函數創建代碼(這是屬性語法所代表的)。
例如,您可能有:
[Attribute2("value of attribute 2")]
void MyMethod(){}
Attribute2
可以定義為:
public class Attribute2 : Attribute {
public Attribute2(string value) { }
public Attribute2() {}
public string Value{get;set;}
}
沒有辦法知道它是否是由...生成的
[Attribute2("value of attribute 2")]
或者
[Attribute2(Value="value of attribute 2")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.