I would like to analyse a switch statement, that uses a "nullable enum" to decide. 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?
). This makes the property EnumUnderlyingType
etc. 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?
Nullable<>
is just a generic. 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. Here is my solution:
if (namedType.IsGenericType)
{
INamedTypeSymbol typeSymbol = namedType.TypeArguments.FirstOrDefault() as INamedTypeSymbol;
if (typeSymbol == null)
{
return;
}
expressionType = typeSymbol;
namedType = typeSymbol;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.