c# - Nullable.GetUnderlyingType 无法正常工作

标签 c# .net types methods nullable

我有以下代码:

Tuple<string, string, Type, ParameterInfo[]> method = (Tuple<string, string, Type, ParameterInfo[]>)(comboBox1.SelectedItem);
if (comboBox2.SelectedIndex - 1 >= 0)
{
    if (method.Item4[comboBox2.SelectedIndex - 1].ParameterType.BaseType == typeof(Enum))
    {
        foreach (object type in Enum.GetValues(method.Item4[comboBox2.SelectedIndex - 1].ParameterType))
        {
            Console.WriteLine(type);
        }
        MessageBox.Show("This looks like an auto-generated type; you shouldn't set it to anything.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
    }
    else if (Nullable.GetUnderlyingType(method.Item4[comboBox2.SelectedIndex - 1].ParameterType) != null)
    {
        if (Nullable.GetUnderlyingType(method.Item4[comboBox2.SelectedIndex - 1].ParameterType).BaseType == typeof(Enum))
        {
            MessageBox.Show("This looks like an auto-generated type; you shouldn't set it to anything.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
        }
    }
}

在 else if 语句中,我注意到它总是返回 null,即使在我的例子中 method.Item4[0] 处的对象在 comboBox2.SelectedIndex 为 1 时始终是 Nullable 类型,那么为什么它返回 null ?说真的,我在那里放了一个断点,在 Item4 中,我看到索引 0 处的对象为:

[0] = {System.Nullable`1[CarConditionEnum]& carCondition}

...在索引 1 处为:

[1] = {Boolean& carConditionSpecified}

最佳答案

问题是参数是引用类型,即它被声明为 ref CarConditionEnum?参数名.

需要获取参数的元素类型,然后使用Nullable.GetUnderlyingType:

Type paramType = method.Item4[comboBox2.SelectedIndex - 1].ParameterType;
if(paramType.HasElementType)
{
    paramType = paramType.GetElementType();
}

if(Nullable.GetUnderlyingType(paramType) != null)
{
}

关于c# - Nullable.GetUnderlyingType 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14737958/

相关文章:

c# - 在 Microsoft Sync Framework 中获取更改摘要

c# - 查找正则表达式中的最后一个匹配项

C++:存储/记住模板类的类型

c# - 如何使用 c# 和 selenium 设置通过 savefileto 插件下载的路径

c# - 在C#中将图像转换为图标

c# - 如何使用 DateTime.Today 与 TextBox.Text 的比较验证器?

C 运行时类型检查

Scala 2.10 类型推断因 ADT 失败 - 从 2.9.3 回归

c# - 将C#数组传递给C++ vector

c# - 在设计时更改 AppResources