如何引用其他文件中的变量?

时间:2012-12-10 05:47:05

标签: c# winforms

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

这是我的代码:

Settings.cs(Windows窗体文件)

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(类文件)

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.height能够从textBoxWidthtextBoxHeight获取文字。

我无法改变

public void button1_Click(object sender, EventArgs e)

到其他任何地方,因为它会破坏表单的功能,所以我不知道该怎么做。

2 个答案:

答案 0 :(得分:2)

向SetWindowSize类添加新方法并从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);
}

答案 1 :(得分:0)

无需更改按钮单击事件处理程序的签名,另一个类也不应该调用该函数。按钮单击事件处理程序应该创建SetWindowSize的实例并调用Write。您可以向Write添加其他参数,以便从按钮单击处理程序传递两个字符串。

相关问题