【问题标题】:Get the actual enum type from a nullable enum type in a switch statement during roslyn analyis在 roslyn analyis 期间从 switch 语句中的可空枚举类型获取实际枚举类型
【发布时间】:2020-11-18 13:04:25
【问题描述】:

我想分析一个使用“可空枚举”来决定的 switch 语句。 我想分析以下课程:

namespace Common.Model.Schema
{
    public enum ModuleType
    {
        Case1,
        Case2,
        Case3
    }   
}

namespace Analyzer.Test
{
    using Common.Model.Schema;

    public class Test
    {
        private static void GetSelectedAblageOrdner()
        {
            ModuleType? moduleType = null;
            switch (moduleType)
            {
                case ModuleType.Case1:
                {
                    break;
                }
            }
        }
    }
}

当开关的输入不可可以为空时,我可以使用以下代码并且我有正确的类型来进行分析。

TypeInfo typeInfo = context.SemanticModel.GetTypeInfo(expression);
ITypeSymbol expressionType = typeInfo.ConvertedType;
if (!(expressionType is INamedTypeSymbol namedType))
{
    return;
}

switch (namedType.EnumUnderlyingType.Name)
{
      // do stuff
}

但是对于可为空的枚举,convertedType 是Nullable<ModuleType>(或者换句话说ModuleType?)。这使得属性EnumUnderlyingType 等为NULL。我需要实际的枚举,以便继续。

如何访问ModuleType,以便继续我对不可为空枚举的默认算法?

【问题讨论】:

    标签: c# roslyn-code-analysis


    【解决方案1】:

    Nullable<> 只是一个泛型。检查它是否是通用的并获取它的参数。

    if (typeof(Nullable<>) == typeInfo.ConvertedType.GetGenericTypeDefinition())
    {
       var actualType = typeInfo.ConvertedType.GetGenericArguments()[0];
    }
    

    【讨论】:

    • 谢谢。虽然这不是解决方案,但我帮我找到了解决方案:)
    【解决方案2】:

    Quercus 为我指明了正确的方向。这是我的解决方案:

    if (namedType.IsGenericType)
    {
        INamedTypeSymbol typeSymbol = namedType.TypeArguments.FirstOrDefault() as INamedTypeSymbol;
        if (typeSymbol == null)
        {
            return;
        }
    
        expressionType = typeSymbol;
        namedType = typeSymbol;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 2021-01-17
      相关资源
      最近更新 更多