我如何使用c#转换为方法 [英] How do i convert to methods using c#

查看:58
本文介绍了我如何使用c#转换为方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码很棒。无需更改任何内容。



我正在尝试使用方法并调用它们(尝试学习如何使用它们)。



那我如何转换 部分用粗体 并用不同的方法重写它们然后在btnCalculate_Click下调用它们。



让我们说第一个。 私人无效checkNumbers()



第二部分让我们说私有空缺值更多()







My code works great. No need to change anything.

I am trying to use methods and call them(trying to learn how to use them).

So How can I convert the sections in bold and rewrite them in separate methods and then call them under the btnCalculate_Click.

Lets say for the first one. Private void checkNumbers() and

for the second part Lets say Privite void valuemorethan()



private void btnCalculate_Click(object sender, EventArgs e)
        {

            try
            {

                //  Variables
                double dFirstNumber;
                double dSecondNumber;
                double dResult = 0;



                //check if First number is valid or not if blank, warn
                if (double.TryParse(txtFirstNumber.Text, out dFirstNumber))
                {


                }
                else
                {

                    MessageBox.Show("First Number contains invalid data.");
                    txtFirstNumber.Focus();

                    return;
                }


                {
                    //check if Second  number is valid or not 
                    if (double.TryParse(txtSecondNumber.Text, out dSecondNumber))
                    {

                    }
                    else
                    {

                        MessageBox.Show("Second Number contains invalid data.");
                        txtSecondNumber.Focus();

                        return;
                    }



                    //Warn if radio buttons are NOT checked
                 if (radAdd.Checked == false && radSubtract.Checked == false && radMultiply.Checked == false && radDivide.Checked == false)
                    {
                        MessageBox.Show("You must select one of the Operation buttons.");

                        return;
                    }


                    //warn if First and Second box values are more than 100
                    if (chkMaxNumber.Checked && dFirstNumber > 100)
                    {
                        MessageBox.Show(" First Number must not be more then 100");

                        txtFirstNumber.Focus();


                        return;
                    }

                    else if (chkMaxNumber.Checked && dSecondNumber > 100)
                    {
                        MessageBox.Show(" Second Number  must not be more then 100");


                        txtSecondNumber.Focus();

                        return;
                    }


                    {
                        //Start doing additions if everthing is good.
                        if (radAdd.Checked)
                        {
                            dResult = dFirstNumber + dSecondNumber;

                        }

                        else if (radSubtract.Checked)
                        {
                            dResult = dFirstNumber - dSecondNumber;

                        }

                        else if (radMultiply.Checked)
                        {
                            dResult = dFirstNumber * dSecondNumber;
                        }

                        else if (radDivide.Checked)
                        {
                            dResult = dFirstNumber / dSecondNumber;

                        }
                        //write the result of the performed calculation to the result box
                        txtResult.Text = dResult.ToString("n1");

                    }

                }

            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


        }

    }
}





我尝试了什么:



我试图创建private void btnCalculate_Click上方的方法并放置需要的部分在每个方法中,但不能使它们正常工作。



What I have tried:

I tried to create the methods above the private void btnCalculate_Click and put the sections that needs to be in each method but cannot get them working.

推荐答案

我投了这个问题因为我认为它反映了人们在使用C#时经常关注的问题.NET,用于理解如何实现正式称为关注点分离的东西,将代码的逻辑功能单元分离为可以轻松重用的离散实体,并且作为副作用,有时是主要的使用,将功能单元与不受控制的交互隔离开来。



imho,致力于最大限度地提高代码的可重用性是我们未来扩展代码的目标无需重新编写代码。



让我们从宏观角度看微观视角下的碎片:



a。一个计算器,可以加,减,乘除,两个数字,并显示结果。



b。一个用户界面,有三个TextBoxes,四个RadioButtons和一个按钮。



c。控制逻辑:计算结果的代码



d。用户交互,约束和控制流



d.1。用户必须输入两个有效数字



d.2。用户必须选择一项操作才能使用



d.3。用户必须触发计算



e。将运行时交互映射到运行时UI



e.1。如何让用户在TextBoxes中为输入值输入正确的数字。可以是整数,也可以是十进制等等?

e.1.1。应该在用户出错时通知他们

e.1.2。或者是否应该允许用户输入错误密钥?

e.1.3。允许粘贴到这些TextBox中吗?

e.1.4。考虑其他数据输入选项,如NumericUpDown和MaskedTextBox?



e.2。如何检测和管理RadioButtons

e.2.1。当有效数据不存在时禁用所有这些?



e.3。管理'计算按钮:禁用除非有效数据存在?

e.3.1。处理可能除以零错误,溢出错误等等?



我首先在界面中表达我的整体意图(架构):
I voted this question up because I think it reflects a frequent concern of people progressing, in their use of C# .NET, towards understanding how to achieve what is formally called "separation of concerns," to separate out logical functional units of code into discrete entities that can be re-used easily, and, as both side-effect, and, sometimes, major use, to isolate functional units from uncontrolled interaction.

imho, implicit in striving to maximize the re-usability of code is the goal of making future extensions to the code possible without requiring total re-writing of the code.

Let's look at the "pieces" here from macro perspective to micro perspective:

a. a calculator which can add, subtract, multiply divide, two numbers, and display the result.

b. a user interface with three TextBoxes, four RadioButtons, and a button.

c. the control logic: the code that calculates the result

d. user-interaction, constraints, and flow-of-control

d.1. the user must enter two valid numbers

d.2. the user must select one operation to use

d.3. the user must trigger calculation

e. mapping the run-time interaction to the run-time UI

e.1. how to make the user enters correct numbers in the TextBoxes for the input values. could be integers, could be decimal, etc. ?
e.1.1. should the user be notified when they make an error
e.1.2. or should the user not be allowed to enter a "wrong key" ?
e.1.3. allow pasting into these TextBoxes ?
e.1.4. consider other options for data entry like NumericUpDown, and MaskedTextBox ?

e.2. how to detect and manage the RadioButtons
e.2.1. disable them all when the valid data is not present ?

e.3. managing the 'calculate button: disable unless valid data is present ?
e.3.1. handle possible divide by zero errors, overflow errors, etc. ?

I'd start with expressing my overall intent (architecture) in an Interface:
public interface ICalculator
{
    // user interface objects
    Control Value1Source { set; get; }
    Control Value2Source { set; get; }
    Control CalculateTrigger { set; get; }

    List<Control> OperationSelectors { set; get; }

    // methods
    bool ReadyToCalculate();
    bool ValidateAndTransformDouble(string doublecandidatestring, out double result);
    void Calculate(double d1, double d2);

    // validated data
    double Data1 { set; get; }
    double Data2 { set; get; }
}

想象一下这个蓝图可以引导你构建一个具有计算器特定化身的特定类。



我愿意用代码进一步回答,如果你表明你对这种方法感兴趣,请让我这样做。

Think of this a "blueprint" that can "guide" you in constructing a specific Class with a specific "incarnation" of a Calculator.

I'm willing to respond further, with code, if you show you are interested in this approach, and ask me to do so.


问题在于你所拥有的已经是一种方法了:如果不使它变得更复杂,你就不能真正缩小它 - 因为如果你失败了,你需要退出你的btnCalculate_Click方法。

我是尽管整理一下:

The problem is that what you have is already a method: and you can't really shrink it much without making it even more complicated - because you need to exit from your btnCalculate_Click method if you get a failure.
I'd tidy it up a little though:
private void btnCalculate_Click(object sender, EventArgs e)
    {
    double dFirstNumber;
    double dSecondNumber;
    double dResult = 0;
    if (!double.TryParse(txtFirstNumber.Text, out dFirstNumber))
       {
        MessageBox.Show("First Number contains invalid data.");
        txtFirstNumber.Focus();
        return;
        }
    if (!double.TryParse(txtSecondNumber.Text, out dSecondNumber))
        {
        MessageBox.Show("Second Number contains invalid data.");
        txtSecondNumber.Focus();
        return;
        }



您可以编写一个Validate方法并调用它,但它开始变得像原始方法一样长而且笨重,几乎:


You could write a Validate method and call that, but then it starts to get as long and unwieldy as the original, nearly:

public bool Validate(TextBox tb, out double num, string errMessage)
    {
    if (!double.TryParse(tb.Text, out num))
        {
        MessageBox.Show(errMessage);
        tb.Focus();
        return false;
        }
    return true;
    }
...
    if (!Validate(txtSecondNumber out dSecondNumber, "Second Number contains invalid data.")) return;

我不得不说我更喜欢第一个版本......

I'd have to say I prefer the first version...


这篇关于我如何使用c#转换为方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆