获取可空类型的类型定义会破坏非可空类型的代码

Val*_*mas 3 c# reflection enums nullable

如果您希望看到以下内容,则这是以下问题:Parse to Nullable Enum

Type t = currentProperty.PropertyType;
if (t.GetGenericTypeDefinition() == typeof(Nullable<>))
    t = t.GetGenericArguments().First();
Run Code Online (Sandbox Code Playgroud)

我在第2行得到一个错误,即IF语句.

System.Reflection.TargetInvocationException : Exception has been thrown by the 
target of an invocation. ----> System.InvalidOperationException : This operation 
is only valid on generic types.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
Run Code Online (Sandbox Code Playgroud)

如何在IF语句中执行代码之前测试该条件?

Jus*_*ony 6

以下是有关检查可空类型的MSDN文档

看起来您需要添加以下内容:

if(t.IsGenericType && ...
Run Code Online (Sandbox Code Playgroud)