无法转换类型'System.Windows.Forms.Form中“对象键入'Project.Form1” [英] Unable to cast object of type 'System.Windows.Forms.Form' to type 'Project.Form1'

查看:637
本文介绍了无法转换类型'System.Windows.Forms.Form中“对象键入'Project.Form1”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件使用了一些,我有可用我的形式对公共财产,在油漆的顶部事件本用户控件,我引用父,并把它转换为类型我。表格

I have a UserControl that uses some of the public properties that I have available on my Form, at the top of the Paint event for this UserControl, I reference the Parent of the control and cast it to the type of my Form.

var _parent = (Form1)Parent;

此代码工作然而,在设计视图,抛出一个错误而我在的地方看在用户控件是一个白色的盒子在这篇文章的标题显示错误。堆栈跟踪直接导致了这行代码。

This code works however, in the Design view, an error is thrown and all I see in place of the UserControl is a white box displaying the error in the title of this post. The stacktrace leads directly to this line of code.

现在,我已经通过重新路由通过物业这个转换在我的用户

Right now, I have fixed this error by re-routing this cast through a Property in my UserControl

    public Form1 ControlParent
    {
        get
        {
            if (Parent != null)
            {
                return (Form1)Parent;
            }
            return null;
        }
    }

这是怎样的一个小的多的东西,仅仅打破了设计视图..任何其他的想法?

This is kind of a little much for something that just breaks the Design view.. any other ideas?

推荐答案

根据它看起来像你的孩子代码控制实例已经可以处理 ControlParent 。因此最简单的解决将是只是做以下

Based on the code it looks like your child Control instance can already deal with ControlParent being null. Hence the simplest fix would be to just do the following

public Form1 ControlParent
{
    get
    {
        return Parent as Form1;
    }
}

请注意:一般情况下这是一个坏主意,依靠在 A 控制特定类型的存在的。它可以防止它被重新托管在其他控件和可以打破设计师往往为了提供一个很好的设计经验,围绕做傻事类型。如果你必须依赖于像父值是一个特定类型的确保有,它并不在不同类型的脸上崩溃回落计划。

Note: In general it's a bad idea to depend on the Parent of a Control being of a specific type. It prevents it from being re-hosted in other controls and can break designers which often fudge types around in order to provide a nice design experience. If you must depend on a value like Parent being of a specific type make sure to have a fall back plan which doesn't crash in the face of a different type.

这篇关于无法转换类型'System.Windows.Forms.Form中“对象键入'Project.Form1”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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