gpt4 book ai didi

c# - InvalidCastException : Specified cast is not valid

转载 作者:搜寻专家 更新时间:2023-10-30 22:12:28 27 4
gpt4 key购买 nike

这部分代码负责从键盘捕获用户输入并使用它。当我按下键盘上的某个按钮(例如 C)时,变量 TAG 将其接收为对象(字节)值 3。我无法找出调试器返回以下错误的原因:System.InvalidCastException。指定的转换无效numtag 声明为整数值。怎么了?在这一行 int? tag = (int?) this.pnlAnswers.Controls[num.Value].Tag; - 调试器指向行尾的 .Tag 作为错误。

    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

关于c# - InvalidCastException : Specified cast is not valid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23235606/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com