如何摆脱这个无效的强制转换异常? [英] How to get rid of this invalid cast exception?

查看:92
本文介绍了如何摆脱这个无效的强制转换异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我一直在努力完成我的小项目,或多或少取得了成功,但发现自己面临的问题似乎是我自己无法解决的问题。当我基本上只是重用一个已经有效的函数时,我会抛出一个InvalidCastException。



我试过的:



So, I've been continously working on my little project with more or less success but find myself in front of a problem I seemingly can't solve on my own. I get thrown an InvalidCastException when I'm basically just reusing a function that works already.

What I have tried:

var c = (customerDB)comboBox1.SelectedItem;
newContact.Name = textBox_Contact_Name.Text.Trim();
newContact.Vorname = textbox_Contact_Firstname.Text.Trim();
newContact.FKKunde = c.PKCustomer;

db.Contacts.Add(newContact);
db.SaveChanges();
Close();



以上代码是可行的代码段,下面是没有的代码段。


The above code is the snippet that works, below is the one that doesn't.

var b = (TArticle)comboBox_Article.SelectedItem;
TPosition newPosition = new TPosition();


newPosition.FKArticle = b.PKArticle;
newPosition.Quantity = (int)numericUpDown_Menge.Value;
newPosition.Position = textBox_Position.Text;
db.TPosition.Add(newPosition);
db.SaveChanges();
Close();



对我来说似乎是一样的,但第二个运行不正常。声明var b时抛出异常。


It seems like the same to me, yet the second one doesn't run properly. The exception is thrown when declaring var b.

推荐答案

ComboBox中的项是 customerDB的实例在第一种情况下,但它不是 TArticle 的实例或第二种派生自 TArticle 的类。如果实例属于无法强制转换为所需类型的类,则会出现无效的强制转换异常。



首先使用调试器查找确切的内容所选项目实际上是:当你知道这一点时,你可以开始查看它为什么不是你想象的那样,或者找出你应该将它转换成什么类。
The item in the ComboBox is an instance of a customerDB in the first case, but it isn't an instance of a TArticle or a class derived from TArticle in the second. If the instance is of a class that cannot be cast to the required type, you will get an invalid cast exception.

Start by using the debugger to find out exactly what the selected item actually is: when you know that, you can start looking at why it isn't what you thought it was, or work out what class you should be converting it to.


摆脱InvalidCastException消息的最简单方法是使用 try-catch(C#参考)| Microsoft Docs [ ^ ]阻止。



详情请见:

管理和类型转换(C#编程指南)| Microsoft Docs [ ^ ]

如何:使用as和is Operators安全地进行投射(C#编程指南) Microsoft Docs [ ^ ]

拳击和拆箱(C#编程指南)| Microsoft Docs [ ^ ]
The simplest way to get rid InvalidCastException message is to use try-catch (C# Reference) | Microsoft Docs[^] block.

For further details, please see:
Casting and Type Conversions (C# Programming Guide) | Microsoft Docs[^]
How to: Safely Cast by Using as and is Operators (C# Programming Guide) | Microsoft Docs[^]
Boxing and Unboxing (C# Programming Guide) | Microsoft Docs[^]


这篇关于如何摆脱这个无效的强制转换异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆