首页 > 解决方案 > C#表单类事件

问题描述

所以我有两个类“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#winformsevents

解决方案


错误说,名为des 的Form没有名为的事件RaiseUpdateEvent

只有班级SplashScreenForm有那个事件。

因此,您应该将您的字段定义为类型SplashScreenForm

static SplashScreenForm SplashScreen;

更高级的替代方案:

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

在这种情况下,您可以这样将其转换为您的类型:

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

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


推荐阅读