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

时间:2012-03-19 03:54:27

标签: c# reflection enums nullable

如果您希望看到以下问题,请参阅以下问题:Parse to Nullable Enum

Type t = currentProperty.PropertyType;
if (t.GetGenericTypeDefinition() == typeof(Nullable<>))
    t = t.GetGenericArguments().First();

我在第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)

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

1 个答案:

答案 0 :(得分:6)

Here is the MSDN documentation on checking for nullable types

您似乎需要添加以下内容:

if(t.IsGenericType && ...