简体   繁体   English

从C#中的类访问表单方法和变量,反之亦然

[英]Access form methods and variables from a class and vice versa in C#

I am trying to finds a way to have access to methods and variables of a form and a class from each other using instance. 我试图找到一种方法,可以使用实例互相访问形式和类的方法和变量。 Here is my code: 这是我的代码:

My form code is: 我的表单代码是:

public partial class Form1 : Form
{
    int var1 = 0;

    public Form1()
    {
        InitializeComponent();
        Glob glob = new Glob(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {

    }
}

and my class code is: 我的课程代码是:

public class Glob
{
    private Form1 _form;

    public Glob(Form1 parent)
    {
        _form = parent;
    }

    public int Func1()
    {
        return 10;
        _form.var1 = 10;
    }
}

I can call form methods from my class, but I can not call class methods from button1_Click event! 我可以从类中调用表单方法,但不能从button1_Click事件中调用类方法! What is wrong with my code please? 请问我的代码有什么问题?

This will never set the property: 这将永远不会设置该属性:

public int Func1()
{
    return 10;
    _form.var1 = 10;
}

The function returns before the property is set. 该函数在设置属性之前返回。 You should be getting an unreachable code warning. 您应该收到unreachable code警告。

Also, your var1 variable is private. 另外,您的var1变量是私有的。 You need to make it public (capitalize it too). 您需要将其公开(也要大写)。 This is so it can be accessed outside of where its declared: 这样可以在声明的位置之外访问它:

public int Var1 { get; set; }

In addition.. you want your Glob instance to be form level: 另外,您希望Glob实例处于表单级别:

private Glob _glob;

public Form1()
{
    InitializeComponent();
    _glob = new Glob(this);
}

Then you can call it in the click event: 然后,您可以在点击事件中调用它:

private void button1_Click(object sender, EventArgs e)
{
    _glob.Func1();
}

That's because your scope for glob is local to your constructor. 那是因为您对glob的作用域是构造函数的本地范围。 Declare it as a module level variable and it will work just fine. 将其声明为模块级变量,它将正常工作。

public partial class Form1 : Form
{
    int var1 = 0;
    Glob glob;

    public Form1()
    {
        InitializeComponent();
        glob = new Glob(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        glob.Func1();
    }
}

[Edit] [编辑]

Simon Whitehead's answer gives more detail of the other problems you have, but mine addresses your specific question of "Why can't I call glob from my button click?" 西蒙·怀特海德(Simon Whitehead)的答案提供了您遇到的其他问题的更多详细信息,但是我的解决了您的特定问题:“为什么我不能通过单击按钮来调用glob ?”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM