Nullable.GetUnderlyingType工作不正常

本文关键字:不正常 工作 GetUnderlyingType Nullable | 更新日期: 2023-09-27 17:58:15

我有以下代码:

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,即使方法中的对象也是如此。在我的例子中,当comboBox2.SelectedIndex为1时,Item4[0]总是一个可为null的类型,那么为什么它返回null呢?说真的,我在那里放了一个断点,在第4项中,我看到索引0处的对象为:

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

在索引1处为:

[1] ={Boolean&carConditionSpecified}

Nullable.GetUnderlyingType工作不正常

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

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

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

问题是参数是refout,我可以从与号和&字符中看到。一开始我不知道如何删除它,但事实证明(另一个答案)你使用GetElementType()

我这样复制你的发现:

var t1 = typeof(int?);
string s1 = t1.ToString();  // "System.Nullable`1[System.Int32]"
bool b1 = Nullable.GetUnderlyingType(t1) != null;  // true
var t2 = t1.MakeByRefType();
string s2 = t2.ToString();  // "System.Nullable`1[System.Int32]&"
bool b2 = Nullable.GetUnderlyingType(t2) != null;  // false
// remove the ByRef wrapping
var t3 = t2.GetElementType();
string s3 = t3.ToString();  // "System.Nullable`1[System.Int32]" 
bool b3 = Nullable.GetUnderlyingType(t3) != null;  // true

这里,t1t3是相同类型的ReferenceEquals(t1, t3)