C # Visual Studio как передать значение из подкласса в родительский класс?

Я здесь новичок, а также новичок в программировании на C # в Visual Studio.

Сейчас у меня есть задание по рефакторингу C #.

Это оригинальный класс

Calculator.cs

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

namespace HUANG_Kai_30077528_Assign1
{
    public partial class calculator : Form
    {


        public calculator()
        {
            InitializeComponent();
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void calorieCalculation()
        {
            if (rbtnMale.Checked)
            {
                txtCalories.Text = (66
            + (6.3 * Convert.ToDouble(txtWeight.Text))
            + (12.9 * ((Convert.ToDouble(txtFeet.Text) * 12)
            + Convert.ToDouble(txtInches.Text)))
            - (6.8 * Convert.ToDouble(txtAge.Text))).ToString();
        }
        else
        {
            txtCalories.Text = (655
            + (4.3 * Convert.ToDouble(txtWeight.Text))
            + (4.7 * ((Convert.ToDouble(txtFeet.Text) * 12)
            + Convert.ToDouble(txtInches.Text)))
            - (4.7 * Convert.ToDouble(txtAge.Text))).ToString();
        }
    }

    private void weightCalculation()
    {
        double maleVariable = 50;
        double femaleVariable = 45.5;
        double Formula = (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12) + Convert.ToDouble(txtInches.Text)));

        if (rbtnMale.Checked)
        {
            txtIdealWeight.Text = ((maleVariable + Formula) * 2.2046).ToString();
        }
        else
        {
            txtIdealWeight.Text = ((femaleVariable + Formula) * 2.2046).ToString();
        }
    }

    private void txtFeetValidation()
    {
        double feet;
        if (!double.TryParse(txtFeet.Text, out feet))
        {
            MessageBox.Show("Feet must be a numeric value.");
            txtFeet.Select();
            if (!(Convert.ToDouble(txtFeet.Text) >= 5))
            {
                MessageBox.Show("Height has to be equal to or greater than 5 feet!");
                txtFeet.Select();
                return;
            }
        }
    }

    private void txtInchesValidation()
    {
        double inches;
        if (!double.TryParse(txtInches.Text, out inches))
        {
            MessageBox.Show("Inches must be a numeric value.");
            txtInches.Select();
            return;
        }
    }

    private void txtWeightValidation()
    {
        double weight;
        if (!double.TryParse(txtWeight.Text, out weight))
        {
            MessageBox.Show("Weight must be a numeric value.");
            txtWeight.Select();
            return;
        }
    }

    private void txtAgeValication()
    {
        double age;
        if (!double.TryParse(txtAge.Text, out age))
        {
            MessageBox.Show("Age must be a numeric value.");
            txtAge.Select();
            return;
        }
    }

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        txtFeetValidation();
        txtInchesValidation();
        txtWeightValidation();
        txtAgeValication();

        //Clear old results           
        txtIdealWeight.Text = "";
        txtCalories.Text = "";
        calorieCalculation();
        weightCalculation();
    }

    private void label8_Click(object sender, EventArgs e)
    {

    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void btnAddPatient_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(txtIdealWeight.Text))
        {
            Form secondForm = new patientInfo(this);
            secondForm.Show();

        }
        else
        {
            MessageBox.Show("Please enter all datas and click on 'Add Patient' to add patient's records");
        }


    }

    private void btnPatientList_Click(object sender, EventArgs e)
    {
        Form secondForm = new patientList(this);
            secondForm.Show();
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        rbtnMale.Checked = false;
        rbtnFemale.Checked = false;
        txtFeet.Text = "";
        txtInches.Text = "";
        txtWeight.Text = "";
        txtAge.Text = "";
        txtCalories.Text = "";
            txtIdealWeight.Text = "";

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }
    }
}

Следующие классы - это родительский класс и подклассы, которые я хотел бы настроить.

родитель: Calculator.cs

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

namespace HUANG_Kai_30077528_Assign1
{
    public partial class calculator : Form
    {
        //private string maleCaloriesCalculation();
        //private string maleWeightCalculation();
        //private string femaleCaloriesCalculation();
        //private string femaleWeightCalculation();

        public calculator()
        {
            InitializeComponent();
        }

        private void rbtnMale_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            //Clear old results           
            txtIdealWeight.Text = "";
            txtCalories.Text = "";


            /* Validate User Input: */
            //Validate height (feet) is numeric value
            double result;
            if (!double.TryParse(txtFeet.Text, out result))
            {
                MessageBox.Show("Feet must be a numeric value.");
                txtFeet.Select();
                return;
            }
            //Validate height (inches) is numeric value
            if (!double.TryParse(txtInches.Text, out result))
            {
                MessageBox.Show("Inches must be a numeric value.");
                txtInches.Select();
                return;
            }
            //Validate weight is numeric value
            if (!double.TryParse(txtWeight.Text, out result))
            {
                MessageBox.Show("Weight must be a numeric value.");
                txtWeight.Select();
                return;
            }
            //Validate age is numeric value
            if (!double.TryParse(txtAge.Text, out result))
            {
                MessageBox.Show("Age must be a numeric value.");
                txtAge.Select();
                return;
            }

            if (!(Convert.ToDouble(txtFeet.Text) >= 5))
            {
                MessageBox.Show("Height has to be equal to or greater than 5 feet!");
                txtFeet.Select();
                return;
            }

            /*End validation*/
            calculation();
        }

        private void calculation()
        {
            if (rbtnMale.Checked)
            {
                txtCalories.Text = maleCalculator.maleCalories().ToString();
                //txtCalories.Text = maleCalculator.maleCaloriesCalculation();
                //txtIdealWeight.Text = maleCalculator.maleWeightCalculation();
            }
            else
            {
                txtCalories.Text = femaleCalculator.femaleCaloriesCalculation();
                txtIdealWeight.Text = femaleCalculator.femaleWeightCalculation();
            }
        }

       private void btnClear_Click(object sender, EventArgs e)
        {
            rbtnMale.Checked = false;
            rbtnFemale.Checked = false;
            txtFeet.Text = "";
            txtInches.Text = "";
            txtWeight.Text = "";
            txtAge.Text = "";
            txtCalories.Text = "";
            txtIdealWeight.Text = "";

        }
    }
}

подкласс: maleCalculation.cs

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

namespace HUANG_Kai_30077528_Assign1
    {
    class maleCalculator: calculator
    {
        //private string maleCaloriesCalculation;
        //private string maleWeightCalculation;

        public maleCalculator maleCalories()
        {
            (66 + (6.3 * Convert.ToDouble(txtWeight.Text))
            + (12.9 * ((Convert.ToDouble(txtFeet.Text) * 12)
            + Convert.ToDouble(txtInches.Text)))
            - (6.8 * Convert.ToDouble(txtAge.Text))).ToString();

            return maleCalories();
            //this.txtCalories.Text = new maleCalculator.maleCalories;
        }

        public maleCalculator maleWeight()
        {
            ((50 + (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12)
            + Convert.ToDouble(txtInches.Text)))) * 2.2046).ToString();

            return maleWeight();
        }
    }
}

подкласс: femaleCalculation.cs

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

namespace HUANG_Kai_30077528_Assign1
{
    class femaleCalculator : calculator
    {
        public double femaleCaloriesCalculation()
        {
            txtCalories.Text = (655 + (4.3 * Convert.ToDouble(txtWeight.Text))
            + (4.7 * ((Convert.ToDouble(txtFeet.Text) * 12)
            + Convert.ToDouble(txtInches.Text)))
            - (4.7 * Convert.ToDouble(txtAge.Text))).ToString();

            return femaleCaloriesCalculation();
        }

        public double femaleWeightCalculation()
        {
            txtIdealWeight.Text = ((45.5 + (2.3 * (((Convert.ToDouble(txtFeet.Text) - 5) * 12)
            + Convert.ToDouble(txtInches.Text)))) * 2.2046).ToString();

            return femaleWeightCalculation();
        }
    }
}

Как мы видим, эти два подкласса используются для расчета калорий и идеального веса. Планируется, что они заменят приватный void calorieCalculation () и приватный void weightCalculation () в исходном классе Calculator.cs.

Мне нужна такая функция:

Когда я запускаю программу и мне нужно вычислить idealWeight и калорий, родительский класс Calculator.cs получит результат из формулы, содержащейся в подклассе, и ToString в текстовом поле. Вот почему в файле Calculator.cs есть txtCalories и txtIdealWeight.

Итак, вопрос в том, как получить результаты в подклассе и заполнить текстовые поля?

Ребята, помогите, пожалуйста, это очень важно для меня !!

Спасибо вам всем!!


person hkmax721    schedule 04.05.2013    source источник


Ответы (1)


Вы имеете в виду виртуальную функцию? Если так,

class Ancestor
{
    public virtual int DoSomething()
    {
        // execute commands here.
        // for now just throw exception.
        throw new NotImplementedException();
    }
}

class Derived_A : Ancestor
{
    public override int DoSomething()
    {
        return 1 + 1;
    }
}

class Derived_B : Ancestor
{
    public override int DoSomething()
    {
        return 1 + 2;
    }
}

Это родословная с виртуальными функциями. Подробнее об этом:

Этот тип кода также может быть выполнен с помощью интерфейсов. См. http://msdn.microsoft.com/en-us/library/vstudio/ms173156.aspx.

person WhyMe    schedule 04.05.2013
comment
Спасибо за помощь. Но я пытаюсь один раз, но безуспешно. Как видите, в родительском классе Calculator.cs есть еще одно if и else в рамках частного вычисления void (). И этот метод вычисления () будет использоваться для автоматического заполнения определенных текстовых полей в зависимости от пола. Так что мне нужно, чтобы я мог вызвать результат формулы расчета, содержащейся в подклассе, установить ToString в текстовом поле в файле Calculator.cs при запуске этой программы. - person hkmax721; 04.05.2013
comment
Я не понимаю ваш комментарий, или я не понял вопроса. Вы можете прояснить это? - person WhyMe; 17.05.2013
comment
Ладно, не суть. Задание было сдано на прошлой неделе. Просто оставь это. Спасибо за помощь !! - person hkmax721; 17.05.2013