[英]Get the actual enum type from a nullable enum type in a switch statement during roslyn analyis
I would like to analyse a switch statement, that uses a "nullable enum" to decide.我想分析一个 switch 语句,它使用“可为空枚举”来决定。 I have the following class that I would like to analyze:
我有以下课程要分析:
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;
}
}
}
}
}
When the input of the switch is not nullable, I can use the following code and I have the correct type to do my analysis on.当开关的输入不可为空时,我可以使用以下代码并且我有正确的类型来进行分析。
TypeInfo typeInfo = context.SemanticModel.GetTypeInfo(expression);
ITypeSymbol expressionType = typeInfo.ConvertedType;
if (!(expressionType is INamedTypeSymbol namedType))
{
return;
}
switch (namedType.EnumUnderlyingType.Name)
{
// do stuff
}
But with nullable enum the convertedType is Nullable<ModuleType>
(or in other words ModuleType?
).但是对于可空枚举,convertedType 是
Nullable<ModuleType>
(或者换句话说ModuleType?
)。 This makes the property EnumUnderlyingType
etc. NULL.这使得属性
EnumUnderlyingType
等为 NULL。 I need the actual enum so I can continue.我需要实际的枚举,以便我可以继续。
How do I get to the ModuleType
, so I can continue my default algorithm I have for non-nullable enums?我如何获得
ModuleType
,以便我可以继续我对不可为空枚举的默认算法?
Nullable<>
is just a generic. Nullable<>
只是一个泛型。 Check that it is generic and fetch its argument.检查它是否是通用的并获取它的参数。
if (typeof(Nullable<>) == typeInfo.ConvertedType.GetGenericTypeDefinition())
{
var actualType = typeInfo.ConvertedType.GetGenericArguments()[0];
}
Quercus pointed me in the right direction. Quercus 为我指明了正确的方向。 Here is my solution:
这是我的解决方案:
if (namedType.IsGenericType)
{
INamedTypeSymbol typeSymbol = namedType.TypeArguments.FirstOrDefault() as INamedTypeSymbol;
if (typeSymbol == null)
{
return;
}
expressionType = typeSymbol;
namedType = typeSymbol;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.