简体   繁体   English

在C#中的哪里声明变量

[英]Where to declare variables in C#

I have created a simple calculator using VS 2013 Pro... and here is the segment of the codes: 我使用VS 2013 Pro创建了一个简单的计算器...这是代码段:

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 CalcTwo
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }


    string input = string.Empty;
    double numb1, numb2, result;


    private void button1_Click(object sender, EventArgs e)
    {
        double.TryParse(textBox1.Text, out numb1);
        double.TryParse(textBox2.Text, out numb2);
        result = numb1 + numb2;
        textBox3.Text = result.ToString();
    }

    private void button4_Click(object sender, EventArgs e)
    {
        double.TryParse(textBox1.Text, out numb1);
        double.TryParse(textBox2.Text, out numb2);
        result = numb1 - numb2;
        textBox3.Text = result.ToString();
    }
}
}

now the problem I'm facing is, I've got two more buttons for multiplying and dividing, which in turn forces me to copy paste double.TryParse(textBox1.Text, out numb1); double.TryParse(textBox2.Text, out numb2); 现在我面临的问题是,我还有两个用于乘法和除法的按钮,这又迫使我复制粘贴为double.TryParse(textBox1.Text, out numb1); double.TryParse(textBox2.Text, out numb2); double.TryParse(textBox1.Text, out numb1); double.TryParse(textBox2.Text, out numb2);

for each button. 每个按钮。 I tried to put the codes with the other variables(double numb1, numb2, result) but getting an error... Here is the screenshots 我试图将代码与其他变量(双numb1,numb2,结果)放在一起,但出现错误...这是屏幕截图

在此处输入图片说明

这是错误消息

Pretty new to Visual Studio and C#. Visual Studio和C#的新手。 Help is appreciated! 感谢帮助! :) :)

The declaration of the variables is fine at the class level. 在类级别上可以很好地声明变量。 However, in order to reduce the code duplication you can extract that specific functionality into its own method. 但是,为了减少代码重复,您可以将该特定功能提取到其自己的方法中。 Something like this perhaps: 大概是这样的:

private void CaptureValues()
{
    double.TryParse(textBox1.Text, out numb1);
    double.TryParse(textBox2.Text, out numb2);
}

Then in the handlers: 然后在处理程序中:

private void button1_Click(object sender, EventArgs e)
{
    CaptureValues();
    result = numb1 + numb2;
    textBox3.Text = result.ToString();
}

This gives you a convenient place to put additional code. 这使您可以方便地放置其他代码。 Checking the inputs and displaying a message, for example: 检查输入并显示一条消息,例如:

private void CaptureValues()
{
    if (!double.TryParse(textBox1.Text, out numb1))
        // textBox1 couldn't be parsed, show an error message
    if (!double.TryParse(textBox2.Text, out numb2))
        // textBox2 couldn't be parsed, show an error message
}

You could even go a step further and put the values into class-level properties. 您甚至可以更进一步,将值放入类级别的属性中。 Something like this: 像这样:

private double Value1
{
    get
    {
        double result;
        if (!double.TryParse(textBox1.Text, out result))
            throw new Exception("Couldn't parse the first text box!");
        return result;
    }
}

private double Value2
{
    get
    {
        double result;
        if (!double.TryParse(textBox2.Text, out result))
            throw new Exception("Couldn't parse the second text box!");
        return result;
    }
}

With those, you don't need your numb1 or numb2 variables at all, just reference the properties directly: 有了这些,您根本不需要numb1numb2变量,只需直接引用属性即可:

textBox3.Text = (Value1 + Value2).ToString();

Currently the properties can throw exceptions, so you might want to handle that: 当前,属性可以引发异常,因此您可能需要处理以下异常:

try
{
    textBox3.Text = (Value1 + Value2).ToString();
}
catch (Exception ex)
{
    // examine what happened with ex and show an error
}

You can throw a more specific Exception type of course, even a custom one. 当然,您可以抛出更特定的Exception类型,甚至是自定义类型。 Or you can respond to the error in the properties instead of in the handlers and not use exceptions at all. 或者,您可以在属性中而不是在处理程序中响应错误,并且根本不使用异常。 (There's an argument to be made, and I agree with it, never to use exceptions for normal logic, and this is potentially one of those edge cases. If it's normal logic, don't use exceptions. If it's an exceptional case and the value should never be un-parseable, go ahead and use them. I'd prefer not to in this case, but was just adding it as a possibility.) (有一个论点,我同意,永远不要在异常逻辑中使用异常,这可能是那些极端情况之一。如果是正常逻辑,则不要使用异常。如果是异常情况,并且值永远不可解析,请继续使用它们。在这种情况下,我不希望这样做,而只是将其添加为一种可能性。)

There are a lot of options. 有很多选择。

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

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