Adding custom attributes to C# classes using Roslyn

后端 未结 1 1231
南旧
南旧 2020-12-30 06:40

Consider the following class in a file \"MyClass.cs\"

using System;

public class MyClass : Entity
{
    public long Id
    {
        get;
               


        
相关标签:
1条回答
  • 2020-12-30 07:20

    One of the parameters of the Syntax.PropertyDeclaration method is a list of attributes that apply to the attribute. Like all Syntax elements, it is constructed using a factory method on the static SyntaxFactory class.

    The Roslyn Quoter can be handy for figuring out how to generate syntax using Roslyn.

    In your particular example, the VisitPropertyDeclaration method of your rewriter should look something like:

    using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
    ...
    
        protected override SyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node)
    {
        var typeSyntax = node.Type;
    
        if (node.Identifier.ValueText == "Id")
        {
            typeSyntax = SyntaxFactory.IdentifierName("string");
        }
    
        var newProperty = PropertyDeclaration(
                    PredefinedType(
                        Token(SyntaxKind.LongKeyword)),
                    Identifier("Id"))
                .WithModifiers(
                    TokenList(
                        Token(SyntaxKind.PublicKeyword)))
                .WithAccessorList(
                    AccessorList(
                        List(new AccessorDeclarationSyntax[]{
                            AccessorDeclaration(
                                SyntaxKind.GetAccessorDeclaration)
                            .WithSemicolonToken(
                                Token(SyntaxKind.SemicolonToken)),
                            AccessorDeclaration(
                                SyntaxKind.SetAccessorDeclaration)
                            .WithSemicolonToken(
                                Token(SyntaxKind.SemicolonToken))})))
                .NormalizeWhitespace();
    
        return newProperty;
    }       
    
    0 讨论(0)
提交回复
热议问题