【发布时间】:2013-01-22 04:13:14
【问题描述】:
我有以下代码:
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}
【问题讨论】:
-
很难从您在此处提供的代码中重现。显然
ParameterInfo显示为{System.Nullable`1[CarConditionEnum]& carCondition}应该有一个ParameterType即CarConditionEnum?,所以可以为空。你确定数组的索引是正确的吗? -
@JeppeStigNielsen - 好吧,如果在第一个 if 语句下我包括这两行: string s1 = method.Item4[comboBox2.SelectedIndex - 1].ParameterType.ToString();字符串 s2 = method.Item4[comboBox2.SelectedIndex - 1].ToString(); ...断点会告诉我 s1 是:s1 = "System.Nullable
1[CarConditionEnum]&" ...and s2 is: s2 = "System.Nullable1[CarConditionEnum]& carCondition" -
另一个提示:不要说
.BaseType == typeof(Enum)(两个地方),你可以简单地使用.IsEnum。
标签: c# .net types methods nullable