如何从一个类调用Method到另一个类

时间:2016-07-23 06:47:00

标签: c#

我需要在c#中调用从一个类到另一个类的一些方法。它与其他答案不同,因为我似乎无法找到我正在寻找的具体答案。

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

namespace IT2127P2_150538B
{
public partial class InputForm : Form
{
    const double cupCakePrice = 1.50;
    int noOfCupcakes, loyaltyPoints;
    double TotalPrice;
    int[] price = new int[15];
    public InputForm()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {

    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form Summaryform = new SummaryForm();
        Summaryform.ShowDialog();

        noOfCupcakes = int.Parse(txtNoOfCupcakes.Text);
        TotalPrice = noOfCupcakes * cupCakePrice;
        if (txtMemId.Text != "")
        {
            if ( noOfCupcakes / 2 > 0)
            {
                loyaltyPoints = (((noOfCupcakes - 1) / 2) * 3) + 1;

            }
            else
            {
                loyaltyPoints = (noOfCupcakes / 2) * 3;
            }
        }
        else
            {
            loyaltyPoints = 0;
            }
        } 
    }
}
}

上面的代码是完成计算的主类。现在,我必须在下面的代码中显示蛋糕数量,忠诚度积分和总蛋糕价格。我的问题是我似乎无法找到一种方法将主类中的变量调用到辅助类。

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

namespace IT2127P2_150538B
{
public partial class SummaryForm : Form
{
    const double cupcakePrice = 1.50;
    public SummaryForm()
    {
        InitializeComponent();
    }

    private void SummaryForm_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Close();
    }




}
}

2 个答案:

答案 0 :(得分:0)

假设您正在调用" SummaryForm"通过" InputForm",然后简单地重载第二类的构造函数,即SummaryForm,并通过它传递信息。即。

public SummaryForm(double dblCupcakes, int intLoyaltyPoints, int intTotalCupcakePrice)
{
    InitializeComponent();
}

然后在InputForm类中创建对象时使用此构造函数。

希望这有帮助

答案 1 :(得分:0)

您有两种选择,要么通过SummaryForm construtor传递值。

public SummaryForm(int cupcakes, int loyaltypoints, double totalprice)

或确保您的变量是公共静态的。然后你可以得到他们的价值观。

// InputForm class.
public static int noOfCupcakes, loyaltyPoints;
public static double TotalPrice;

// SummaryForm class.
InputForm.noOfCupcakes;
InputForm.loyaltyPoints;
InputForm.TotalPrice;