The end goal is to copy the attributes "as is" from a method to another method in a generated class.
public class MyOriginalClass
{
[Attribute1]
[Attribute2("value of attribute 2")]
void MyMethod(){}
}
public class MyGeneratedClass
{
[Attribute1]
[Attribute2("value of attribute 2")]
void MyGeneratedMethod(){}
}
I am able to list the attribute of the method using MethodInfo.GetCustomAttributes() however, this does not give me the attributes arguments; which I need to generate the corresponding attribute on the generated class.
Note that I don't know the type of the attributes (can't cast the Attribute).
I am using CodeDom to generate code.
MethodInfo.GetCustomAttributesData() has the needed information:
// 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()));
}
I don't see how it would be possible to do this. GetCustomAttributes returns an array of objects, each of which is an instance of a custom attribute. There's no way to know which constructor was used to create that instance, so there's no way to know how to create the code for such a constructor (which is what the attribute syntax amounts to).
For instance, you might have:
[Attribute2("value of attribute 2")]
void MyMethod(){}
Attribute2 may be defined as:
public class Attribute2 : Attribute {
public Attribute2(string value) { }
public Attribute2() {}
public string Value{get;set;}
}
There's no way to know if it was generated by
[Attribute2("value of attribute 2")]
or by
[Attribute2(Value="value of attribute 2")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With