最终目标是将属性“按原样”从一个方法复制到生成的类中的另一个方法。
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()));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句