繁体   English   中英

来自C#中另一个类的对象

[英]Objects from another Class In C#

我想在表单类中使用2个类(1个表单类),我称另一个类为空。 它可以工作而且我想用标签和文本框(在第二堂课脚本中)做thig,我看到了这个如何从另一个班级更改标签? C#Windows Forms Visual Studio和我的代码:

`private new void Enter(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                Commands.OnCommand();`

其他班:

public static void OnCommand()
    {
        Form1 frm = new Form1();
        if (frm.code.Text.Contains("end") && frm.code.TextLength == 4)
        {
            if (MessageBox.Show("Close?", "Close window?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                frm.Close();
            }
            else
            {
                frm.output.Text = (frm.output.Text + "\nClosing closed").ToString();
                frm.code.Clear();
            }
        }
        else
        {
            MessageBox.Show("test");
            frm.output.Text = (frm.output.Text + "\nI don't understand ... ").ToString();
            frm.code.Clear();
        } /**/

它只在末尾显示消息框....我认为错误是在声明form1

您必须传递对原始表单的引用,而不是为其创建新实例:

private new void Enter(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == Convert.ToChar(Keys.Enter))
    {
        Commands.OnCommand(this);



public static void OnCommand(Form1 frm)
{
    if (frm.code.Text.Contains("end") && frm.code.TextLength == 4)
    {

话虽如此,我认为将对整个Form的引用发送到另一种方法中是不明智的做法。 相反,请尝试对其进行重组,以便仅传递该方法所需的那些值(例如code.Text ),并使其返回Form需要显示的值。

private new void Enter(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == Convert.ToChar(Keys.Enter))
    {
        string message = Commands.OnCommand(code.Text);

        if (message == "")
        {
            Close();
        }
        else
        {
            frm.output.Text = frm.output.Text + message;
            frm.code.Clear();
        }



public static void OnCommand(string code)
{
    if (code.Contains("end") && code.Length == 4)
    {
        if (MessageBox.Show("Close?", "Close window?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            return "";
        else
            return "Closing closed";
    }
    else
    {
        MessageBox.Show("test");
        return "I don't understand ... ";
    }

暂无
暂无

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

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