繁体   English   中英

如何从WinForm中调用类中的方法?

[英]How can I call a method in a class from a WinForm?

我是winforms的新手,也是c#的初学者。 我使用else创建了一个简单的应用程序。 用户输入0到10之间的值并按下按钮。 如果该数字介于该范围之间,则会弹出一个消息框,同时显示一条消息以及输入的数字。 但如果该数字高于10,则会弹出一个消息框,说“该数字必须低于10”。 到目前为止,我已经完成了所有这些工作,但现在我想让类处理它背后的逻辑,但我不知道如何使class1.cs和Form1.cs访问彼此的信息。 据我所知,Class1.cs是从Form1获取值,分析它并返回一个值。 然后Form1.cs将获取返回的值并显示它 - 我是吗? - 。 但我不知道该怎么做。

我在这里问的基本上是,如果你能告诉我我必须把什么放到我的class1.cs中,所以它会在自己内部执行if / else逻辑, 而不是在Form1.cs中执行它(就像现在这样)。

感谢大伙们 !

Form1.cs的

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void btnDone_Click(object sender, EventArgs e)
        {

            double number = Convert.ToDouble(txtNumber.Text);

            if (number > 10)
            {
                MessageBox.Show("Number must be below 10");

            }
            else {
                MessageBox.Show("Good !  You entered : " + number);
            }
        }
    }
}

将Class1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication2
{
    class Class1
    {

    }
}
public static class Class1
{
    public static string GetIsValidNumberMessgae(string text)
    {
        string message;
        int number;
        if(int.TryParse(text,out number))
        {
            if (number > 10)
                message="Number must be below 10";
            else 
                message="Good !  You entered : " + number;
        }
        else
            message="Not valid number";
        return message;
    }
}

和:

    private void btnDone_Click(object sender, EventArgs e)
    {
        MessageBox.Show(Class1.GetIsValidNumberMessgae(txtNumber.Text));
    }
private void label1_Click(object sender, EventArgs e)
{
        Class1 cls = new Class1();
        // cls.methodName(parameters);
}

你需要传递“form1”实例化到class1:

就像是:

Class1 class1 = new Class1(this);

在class1:

namespace WindowsFormsApplication2 { 
  public class 1 { 
  private Form1 form1;

  public Class1(Form1 Form1) {
      form1 = Form1;
  }

  public GetTxtMessage() {
     return form1.txtNumber.Text;
  }
 }
}

暂无
暂无

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

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