【问题标题】:Getting type definition for nullable types breaks code for non-nullable types获取可空类型的类型定义会破坏不可空类型的代码
【发布时间】:2012-03-19 12:00:05
【问题描述】:

如果您想查看,这是对以下问题的后续问题: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 语句中的代码之前测试该条件?

【问题讨论】:

    标签: c# reflection enums nullable


    【解决方案1】:

    Here is the MSDN documentation on checking for nullable types

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

    if(t.IsGenericType && ...
    

    【讨论】:

    • 为什么要删除赞成票?这没有回答您的具体问题吗?
    猜你喜欢
    • 2020-12-19
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2017-09-25
    • 1970-01-01
    相关资源
    最近更新 更多