从另一个类调用主类的公共方法 [英] Call a public method of main class from another class

查看:34
本文介绍了从另一个类调用主类的公共方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要Form1.cs如下

   public partial class Form1: Form
    {
        Test _Test = new Test()

        public Form1()
        {
            InitializeComponent();
            _Test._TestMethod();
        }

        public void _MainPublicMethod(string _Message, string _Text)
        {
            MessageBox.Show(_Message);
            TextBox1.Text = Text;
        }
    }

我的Test.cs如下

class Test
{
    Form1 _Form1 = new Form1();

    public void _TestMethod()
    {
        _Form1._MainPublicMethod("Test Message", "Test Text");
    }
}

当我调试我的项目时,代码不起作用.

When i debug my project, codes doesn't work.

提前致谢.

推荐答案

您的代码显示了一个常见的误解(或缺乏对基本 OOP 原则的理解).
当在 form1 中,您的代码调用 _Test._TestMethod() 时,您正在调用属于"在 form1 中定义和初始化的类 Test 的实例的方法.反过来,该实例尝试调用在类 Form1 中定义的方法 _MainPublicMethod.但是,因为要调用该方法(实例方法,而不是静态方法),您需要一个 Form1 的实例,所以您声明并初始化了 Form1 的 ANOTHER 实例

Your code shows a common misunderstanding (or a lack of understanding of a basic OOP principle).
When, inside form1, your code calls _Test._TestMethod() you are calling a method that 'belongs' to the instance of class Test defined and initialized in your form1. In turn, that instance try to call the method _MainPublicMethod defined in the class Form1. But, because to call that method (an instance method, not a static method) you need an instance of Form1, you declare and initialize ANOTHER instance of Form1

您最终打开了类 Form1 的两个实例,并且调用由 Form1 的第二个实例而不是最初调用 _TestMethod 的实例解析.

You end up with two instances of the class Form1 opened and the call is resolved by the second instance of Form1 not from the instance that had called _TestMethod initially.

为了避免这个问题,您需要传递对调用 Test_Method 的 Form1 实例的引用,并在 Test 内部使用该实例来回调公共方法.

To avoid this problem you need to pass the reference to the instance of Form1 that calls Test_Method and use that instance inside Test to call back on the public method.

所以,当调用 Test_Method 时传递 Form1 的当前实例

So, when calling Test_Method pass the current instance of Form1

   public Form1()
   {
        InitializeComponent();
        _Test._TestMethod(this);
   }

在 Test.cs 中

and in Test.cs

class Test
{
    Form1 _frm = null;

    public void _TestMethod(Form1 f)
    {
        _frm = f;
        _frm._MainPublicMethod("Test Message", "Test Text");
    }
}

这篇关于从另一个类调用主类的公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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