【问题标题】:C# form class eventC#表单类事件
【发布时间】:2021-04-05 15:41:31
【问题描述】:

所以我有两个类“SplashScreenForm”和“Program”,并且在事件中想要运行“MainForm”。 它看起来像这样:

public partial class SplashScreenForm : Form
{
    public event EventHandler<int> RaiseUpdateEvent;
    ........

在“程序”中定义这样的类

static class Program
{
    static Form SplashScreen;
    static Form MainForm;

    SplashScreen = new SplashScreenForm();
    .........

但问题是,当我尝试访问事件时,它说“SplashScreenForm”不包含该事件。我该如何解决这个问题?

SplashScreen.RaiseUpdateEvent += SplashScreen_RaiseUpdateEvent;

错误提示:CS1061 C# 'Form' 不包含定义,并且找不到接受“Form”类型的第一个参数的可访问扩展方法(您是否缺少 using 指令或程序集引用?)

【问题讨论】:

    标签: c# winforms events


    【解决方案1】:

    错误表明,名为Form 没有名为RaiseUpdateEvent 的事件

    只有 SplashScreenForm 类有该事件。

    所以你应该将你的字段定义为SplashScreenForm

    static SplashScreenForm SplashScreen;
    

    更高级的替代方案:

    如果出于某种原因您希望变量 SplashScreen 的类型为 Form(可能是您从无法控制的库中获取类型),您实际上仍然可以使用它,因为 您知道当你打电话给new SplashScreenForm()时它是SplashScreenForm

    在这种情况下,您可以像这样将其投射为您的类型:

    ((SplashScreenForm)SplashScreen).RaiseUpdateEvent += SplashScreen_RaiseUpdateEvent;
    

    现在您要告诉编译器,虽然它被声明为 Form,但它实际上是一个 SplashScreenForm 并且可以用作那个 - 这意味着 cast 类型确实有一个 RaiseUpdateEvent 事件。

    【讨论】:

    • 谢谢,这很有趣,很简单:D
    • 好吧,如果你知道答案,大多数问题都很简单。
    • 是的,您完全正确,Cast 也适用于我的应用程序。太感谢了! ^_^
    猜你喜欢
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 2015-07-19
    相关资源
    最近更新 更多