在C#代码分析中,如何知道typesyntax是否是枚举?

发布于 2025-02-09 18:31:28 字数 418 浏览 0 评论 0原文

在我的代码中,我已经捕获了此typeyntax,这是标识的Namesyntax。如图所示,在“属性”下,这是一个枚举,分类为“枚举名称”。但是我不知道该如何在我的程序中得到这个。似乎与语义模型有关。

它是在给定的genoratoreXecutionContext上下文下完成的,因此可以获取语义模型context.compilation.getSemanticmodel(typeyntax.syntaxtree),您不必担心。

enter image description here

In my code, I have already captured this TypeSyntax, which is an IdentifierNameSyntax. It is an Enum, as shown in the image, under "Properties", the Classification is "Enum Name". But I don't know how to get this in my program. Seem like it have something to do with the semantic model.

It was done under given GeneratorExecutionContext context, so semantic model can be get context.Compilation.GetSemanticModel(typeSyntax.SyntaxTree), you don't need to worry about that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

路还长,别太狂 2025-02-16 18:31:28

您在正确的轨道上!
目前,您手头上有句法信息,您确实可以通过 Semanticmodel

,要求 typeInfo

TypeInfo typeInfo = semanticModel.GetTypeInfo(typeSyntax, context.CancellationToken);
ITypeSymbol? type = typeInfo.Type;

if (type is INamedTypeSymbol { TypeKind: TypeKind.Enum } symbol)
{
    Debug.Assert(type is not IErrorTypeSymbol);
    Debug.Assert(type.SpecialType != SpecialType.System_Enum);
}

首先 获取有关 ,例如 api/system.int32“ rel =“ nofollow noreferrer”> int 默认值:

IEnumerable<string> memberNames = type
    .GetMembers()
    .Where(static member => member.Kind is SymbolKind.Field)
    .Select(static symbol => symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));

INamedTypeSymbol? underlyingType = symbol.EnumUnderlyingType;
Debug.Assert(underlyingType is not null);

You are on the right track!
Currently you have the syntactic information in hand, and you may indeed query semantic information through the SemanticModel.

First, ask for the TypeInfo of that expression:

TypeInfo typeInfo = semanticModel.GetTypeInfo(typeSyntax, context.CancellationToken);
ITypeSymbol? type = typeInfo.Type;

if (type is INamedTypeSymbol { TypeKind: TypeKind.Enum } symbol)
{
    Debug.Assert(type is not IErrorTypeSymbol);
    Debug.Assert(type.SpecialType != SpecialType.System_Enum);
}

With this you can get hold of more semantic information about that enum type, such as its members and their names, or the underlying type of the enum type which is int per default:

IEnumerable<string> memberNames = type
    .GetMembers()
    .Where(static member => member.Kind is SymbolKind.Field)
    .Select(static symbol => symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));

INamedTypeSymbol? underlyingType = symbol.EnumUnderlyingType;
Debug.Assert(underlyingType is not null);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文