重写方法声明

时间:2013-08-13 08:54:32

标签: c# roslyn

我正在迭代一个类型中的方法,并且必须重写那些非静态的方法。我必须插入参数作为第一个或最后一个参数,但无法弄清楚如何创建ParameterSyntax对象

这是我到目前为止所拥有的

var methods = from m in r.Members.OfType<MethodDeclarationSyntax>()
              where !m.Modifiers.Contains(Syntax.Token(SyntaxKind.StaticKeyword))
              select new {
                   orgMethodDecl = m, 
                   rewrittenDecl = RewriteMethodDeclaration(m,name)};

                   var rewrittenType = r;
                   foreach(var m in methods){
                        rewrittenType = rewrittenType.ReplaceNode(m.orgMethodDecl, m.rewrittenDecl);
                   }

RewriteMethodDeclaration是我遇到问题的地方

    MethodDeclarationSyntax RewriteMethodDeclaration(MethodDeclarationSyntax method, string name)
    {
        var p = Syntax.Parameter(); //type dynamic, name: name
        var parameters = method.ParameterList.AddParameters(p);
        return method.WithParameterList(parameters);
    }

1 个答案:

答案 0 :(得分:1)

试试这个:

static MethodDeclarationSyntax 
    RewriteMethodDeclaration(MethodDeclarationSyntax method, string name)
{
    var type = Syntax.ParseTypeName("dynamic");
    var identifier = Syntax.Identifier(String.Format(" {0}", name));
    var p = Syntax.Parameter(
        new SyntaxList<AttributeListSyntax>(),
        new SyntaxTokenList(),
        type,
        identifier,
        null);
    var parameters = method.ParameterList.AddParameters(p);
    return method.WithParameterList(parameters);
}