c# - 如何解决 C# 中的“InvalidCastException”?
问题描述
我收到一个运行时错误,它告诉我它无法将 PictureBox 类型的对象转换为 MusicNote 类型(MusicNote 继承自 PictureBox。)
private void Note_MouseDown(object sender, MouseEventArgs e)
{
//try
//{
foreach (MusicNote mn in panel2.Controls) //this is where the error occurs
{
if (sender == mn)
{
if (e.Button == MouseButtons.Right)
{
count = 0;
timer1.Start();
sp.SoundLocation = MusicNote_path + mn.note + ".wav";
sp.Play();
}
if (e.Button == MouseButtons.Left)
{
dragging = true;
mn.BackColor = Color.HotPink;
}
下面是 MusicNote 类的一部分,包括构造函数,展示了每次构造 MusicNote 时会发生什么:
class MusicNote : PictureBox
{
public int notepitch;
public int noteduration;
public String noteshape;
public String note;
enum Accid { sharp, flat, sole };
public static String NoteImage_path = Environment.CurrentDirectory + @"\Notes-Images\\";
public static int xLoc = 30;
public int yLoc = 0;
System.Timers.Timer timer1 = new System.Timers.Timer();
public MusicNote(int iNotepitch, int iDuration, String iBnoteShape, String iNote)
{
notepitch = iNotepitch;
noteduration = iDuration;
noteshape = iBnoteShape;
note = iNote;
ImageLocation = NoteImage_path + noteshape + ".bmp";
BackColor = Color.Transparent;
ClientSize = new Size(35, 35);
//BringToFront();
Location = new Point(xLoc, getyLoc(iNote));
xLoc += 37;
}
这是面板的填充方式:
MusicNote mn = new MusicNote(mk.getMusicNote(), duration, bNoteShape, mk.getNote());
mn.MouseDown += new MouseEventHandler(Note_MouseDown);
mn.MouseUp += new MouseEventHandler(Note_MouseUp);
mn.MouseClick += new MouseEventHandler(Note_MouseClick);
panel2.Controls.Add(mn); //adding MusicNote component to MusicStaff (panel2) collection
编辑:您可以在此处查看错误。
任何帮助表示赞赏,谢谢。
解决方案
要仅循环MusicNote
实例,您可以使用OfType
LINQ 中的扩展方法:
foreach (MusicNote mn in panel2.Controls.OfType<MusicNote>()) {
// do stuff
}
推荐阅读
- sql - SQL查询优化实践
- python - 我的 Django Python 代码没有更改数据库记录
- html - 旋转div时如何将文本与左侧对齐?
- android - android设备启动后如何执行一些应用程序(没有UI的简单C应用程序)
- swift - Firebase 身份验证 - 使用电话身份验证忘记密码
- firebase - TypeError:navigation.getParam 不是函数 - 反应原生
- azure - Azure 中的 Terraform/HCL 问题
- mysql - 如何在 mysql 中使用 json_object 创建值是动态的对象?
- c# - 带有 NetTopologySuite.IO.GeoJSON 的 JsonConvert.DeserializeObject 有异常 未找到预期令牌“}”
- java - 将 Terracotta 用于(分布式)共享 Java 对象