如何在 Visual Studio 中的窗体之间继承变量,C++
How to inherit variables from between forms in Visual Studio, C++
所以我正在使用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 的实例作为参数。
相关文章:
- ' class a : b ' 和 ' class a : public b ' 之间的继承类不同
- 类 QLayout 和类 QMainWindow Qt c++ 之间的继承
- 接口实现和私有继承之间的交互
- 在多个继承C 之间进行铸造和释放
- 在继承多个空类时,了解GCC/Clang vs MSVC2015之间的不同填充规则
- 如何在模板与并集之间进行继承?
- 如何在继承级别的多个实例之间共享相同的数据
- 在同级之间继承相同的变量名
- 需要对多个类之间继承的C 代码进行帮助重组和/或重新编写此C 代码
- 基础和派生类C 之间的继承数据成员
- 运行时动态绑定和类继承之间的区别
- 分配同一类时上层类和继承类之间的区别
- 继承类型的指针之间的静态强制转换
- 2 个类之间的继承和转换失败了 c++
- 继承类之间的枚举的最佳实践是什么?
- 通过 QI 或继承已知平等之间的区别
- 如何在单独的 Boost.Python 模块之间拆分继承关系
- 如何在 Visual Studio 中的窗体之间继承变量,C++
- 构造函数之间的继承[关闭]
- 使用继承在类之间传递非静态变量