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ステートメントで、comboBox2.SelectedIndexが1の場合、method.Item4 [0]のオブジェクトは常にNullable型であるにもかかわらず、常にnullを返すことに気付きました。なぜ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 に答える