1

我有以下代码:

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}

4

2 回答 2

4

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

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

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

if(Nullable.GetUnderlyingType(paramType) != null)
{
}
于 2013-02-06T20:51:31.307 回答
1

问题是参数是ref或者out我可以从 &&字符中看到。起初我不知道如何删除它,但事实证明(另一个答案)你使用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)

于 2013-02-06T20:41:31.523 回答