如何引用不同文件中的变量? [英] How do I reference variables from a different file?

查看:56
本文介绍了如何引用不同文件中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是将按钮单击事件中的两个变量传递给同一文件中的另一个类.

What I want to do is pass two variables from a button click event to another class in the same file.

这是我的代码:

Settings.cs(Windows 窗体文件)

Settings.cs (Windows Form file)

namespace ShovelShovel

public partial class Settings : Form
{
    public Settings()
    {
        InitializeComponent();
    }

    public void button1_Click(object sender, EventArgs e)
    {
        SetWindowSize.SaveData(textBoxWidth.Text, textBoxHeight.Text);
    }
}
}
}

SetWindowSize.cs(类文件)

SetWindowSize.cs (class file)

namespace ShovelShovel

class SetWindowSize
{
    public static void SaveData(string width, string height)
    {          
        using (BinaryWriter binaryWriter = new BinaryWriter(File.Open("file.dat", FileMode.Create)))
        {
                binaryWriter.Write(width, height);
        }
    }
}
}

我希望 SetWindowSize.cs 中的 Settings.widthSettings.heighttextBoxWidthtextBoxHeight 获取文本代码>.

I want Settings.width and Settings.height in SetWindowSize.cs to get the text from textBoxWidth and textBoxHeight.

我无法改变

public void button1_Click(object sender, EventArgs e)

其他任何东西,因为它会破坏表单的功能,所以我不知道该怎么办.

to anything else, since it would break the function of the form, so I don't know what to do.

推荐答案

向 SetWindowSize 类添加新方法并从 button1_Click 调用它

Add new method to SetWindowSize class and call it from button1_Click

public static class SetWindowSize
{
    public static void SaveData(string width, string height)
    {
        File.WriteAllText("file.dat", string.Format("height: {0}, width: {1}.", height, width));
    }
}    

点击按钮

public void button1_Click(object sender, EventArgs e)
{
    SetWindowSize.SaveData(textBoxWidth.Text, textBoxHeight.Text);
}

这篇关于如何引用不同文件中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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