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

巧了我就是萌 提交于 2019-12-12 01:43:00

问题


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! What is wrong with my code please?


回答1:


That's because your scope for glob is local to your constructor. 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?"




回答2:


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.

Also, your var1 variable is private. 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:

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();
}


来源:https://stackoverflow.com/questions/24398814/access-form-methods-and-variables-from-a-class-and-vice-versa-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!