InvalidCastException:指定的强制转换无效
本文关键字:转换 无效 InvalidCastException | 更新日期: 2023-09-27 17:59:32
这部分代码负责从键盘捕获用户输入并使用它。当我按下键盘变量TAG上的某个按钮(例如C)时,TAG会将其作为对象(字节)值3接收。我找不到调试器返回以下错误的原因:System.InvalidCastException。指定的强制转换无效。num和标记声明为整数值。怎么了?在这行int?tag=(int?)this.pnlAnswers.Controls[num.Value].tag-调试器指向行末尾的.标记为error。
private void Question_KeyDown(object sender, KeyEventArgs e)
{
int? num = null;
this.qta.get_answer_number_by_key(new int?(e.KeyValue), ref num);
if (!num.HasValue)
{
this.SwitchQuestion(e.KeyValue);
}
else
{
num -= 1;
bool? nullable2 = false;
bool? end = false;
if (this.pnlAnswers.Controls.Count >= (num + 1))
{
Valid valid;
int? tag = (int?) this.pnlAnswers.Controls[num.Value].Tag;
this.qta.test_answer(this.q, tag, ref nullable2, ref end, ref this.pass);
this.e = end.Value;
if (nullable2.Value)
{
valid = new Valid(MessageType.Valid);
}
else
{
valid = new Valid(MessageType.Invalid);
}
valid.ShowDialog();
base.Close();
}
}
}
我试着更改
int? tag = (int?) this.pnlAnswers.Controls[num.Value].Tag;
至
byte? tag = (byte?) this.pnlAnswers.Controls[num.Value].Tag;
错误消失了,但是我在接收这些值的后处理方面遇到了问题。
您需要将Tag
属性引用的对象强制转换为其实际类型byte
。然后您可以对byte
对象进行进一步的转换:
byte tagByte = (byte)this.pnlAnswers.Controls[num.Value].Tag);
int? tag = (int?) tagByte;
//or in short :
//int? tag = (byte)this.pnlAnswers.Controls[num.Value].Tag;
我做了一个简单的测试来证实这种行为:
byte initialValue = 3;
object TAG = initialValue;
int? tagSuccess = (int?)((byte)TAG); //successfully convert TAG to type int?
int? tagFails = (int?)TAG; //throw InvalidCastException
接受的答案并不总是有效的。
当在Visual Studio窗体设计器的属性编辑器中将Tag设置为1时,将为其分配字符串类型,即"1"。当异常发生时,您可以在调试器中看到这一点。有引号。
字符串不能直接转换为任何数字类型。在这种情况下,(byte)将产生相同的异常。
对于字符串或整数类型的标记,一个通用但不干净的解决方案是。。
private int TagValue(object cTag)
{
int iTag = 0;
try { iTag = (int)cTag; } catch { iTag = int.Parse((string)cTag); }
return iTag;
}