如何在 Visual Studio 中的窗体之间继承变量,C++

How to inherit variables from between forms in Visual Studio, C++

本文关键字:继承 之间 变量 C++ 窗体 Visual Studio      更新时间:2023-10-16

所以我正在使用Windows表单,我偶然发现了一个问题,当我按下一个按钮时,一个名为Form2的表单打开并且Form1隐藏。但问题是我需要将一个整数变量从 Form1 继承到 Form2,但我无法弄清楚该怎么做......我试图使类 Form2 从 Form1 继承,但这会使 Form2 具有所有控件(文本框、标签等)。那么正确的方法是什么呢?Maby 我已经不连贯地创建了 Form2...

以下是表单类的编写方式。

public ref class Form2 : public System::Windows::Forms::Form
{
public ref class Form1 : public System::Windows::Forms::Form
{

我试过了

 public ref class Form2 : public System::Windows::Forms::Form, public Form1
{

感谢您的关注!

不允许从两个基类继承。您只能从一个类继承,但还可以根据需要实现任意数量的接口。尝试如下:

public ref class Form2 : public Form1 
{ 

在您的情况下,您不需要从两个类继承,因为 Form1 已经继承了 System.Windows.Forms.Form,如果 Form2 继承了 Form1,它也会自动继承 System.Windows.Forms.Form 类型。

如果两个形式应该只有一个变量,没有别的,为什么要使用继承?因为继承通常意味着扩展基类,以便 Form1 的所有成员/属性/方法在 Form2 中也可用。由于窗体必须继承自 System.Windows.Forms.Form,因此不能使用任何其他基类。也许您应该考虑使用将公共变量定义为属性的公共接口,然后,两种形式都必须实现该接口。

public interface IMyForm
{
    int MyValue { get; set; }
}
public class Form1 : System.Windows.Forms.Form, IMyForm
{
   public int MyValue { get; set; }
   ...
}
public class Form2 : System.Windows.Forms.Form, IMyForm
{
   public int MyValue { get; set; }
   ...
}

很抱歉 C# 语法,希望它能明白我的意思。例如,如果您现在有一个方法,该方法需要将该公共属性作为参数的表单,则可以简单地执行此操作:

public void DoSomething(IMyForm form)
{
    form.MyValue = 5;
}

并且可以传递 Form1 或 Form2 的实例作为参数。