How to create struct based properties with Roslyn

六月ゝ 毕业季﹏ 提交于 2019-12-13 16:16:51

问题


I have the following code to generate a property:

Types:

types = new Dictionary<string, SpecialType>();
types.Add("Guid", SpecialType.System_Object);
types.Add("DateTime", SpecialType.System_DateTime);
types.Add("String", SpecialType.System_String);
types.Add("Int32", SpecialType.System_Int32);
types.Add("Boolean", SpecialType.System_Boolean);  

generator.PropertyDeclaration(name, generator.TypeExpression(types["DateTime"]), Accessibility.Public);

However, I always get an exception when the name of a struct type is the parameter (e.g. DateTime or Guid - for Guid, I can't even find a proper special type):

Unsupported SpecialType

  at: Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpSyntaxGenerator.TypeExpression(SpecialType specialType)
  at: MyProject.CreateProperty(String name, String type)

What should I use?


回答1:


You can create properties based upon the name of the type, so you could create DateTime and Guid properties with code such as

// Create an auto-property
var idProperty =
    SyntaxFactory.PropertyDeclaration(
        SyntaxFactory.ParseTypeName("Guid"),
        "Id"
    )
    .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
    .AddAccessorListAccessors(
        SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
        SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
    );

// Create a read-only property, using a backing field
var createdAtProperty =
    SyntaxFactory.PropertyDeclaration(
        SyntaxFactory.ParseTypeName("DateTime"),
        "CreatedAt"
    )
    .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
    .AddAccessorListAccessors(
        SyntaxFactory.AccessorDeclaration(
            SyntaxKind.GetAccessorDeclaration,
            SyntaxFactory.Block(
                SyntaxFactory.List(new[] {
                    SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName("_createdAt"))
                })
            )
        )
    );

If I've missed something obvious that means that you can't use this sort of syntax, would you please edit your answer and include an executable minimum reproduce case?

(I noticed that the "PropertyDeclaration" method in your sample specifies parameters name, type, accessibility which do not correspond to any "PropertyDeclaration" method signatures on the SyntaxFactory class - is that method one that you've written that then calls a SyntaxFactory method?)



来源:https://stackoverflow.com/questions/38205773/how-to-create-struct-based-properties-with-roslyn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!