繁体   English   中英

在C#中将参数传递给方法

[英]Passing an argument to a method in C#

因此,该程序可以正常运行,但是我认为代码不是很“干净”,因此我正在寻找建议。 我有两个大问题:

  1. 对于方法double double temperatureInFahrenheit,我想将参数celsiusTemperature传递给函数,而不必重新声明变量,将其从文本转换为double,等等。每当尝试尝试在MessageBox中遇到错误时,都可以。当我尝试调用函数myAirport.temperatureInFahrenheit时显示(我不特别记得错误是什么,因此如果需要,我将不得不重新编码)。 对我可以做些什么有什么想法?

  2. 公共局部类Form1中的MessageBox.Show对我来说似乎是混乱的代码。 我想做的是在内部类Airport中编写一个方法,将必要的参数传递给该方法,然后执行诸如MessageBox.Show(myAirport.message())之类的操作,但是我假设是否试图让我得到和1一样的错误。有什么想法吗?

同样,该代码可以完全正常工作并且可以满足所需的规范,但是我不只是拥有功能代码,还喜欢拥有“漂亮”的功能代码。 注意:我对任何方法,变量等都没有评论。我现在将其放在注释中,但以为我会先尝试获得一些反馈。

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

    private void button1_Click(object sender, EventArgs e)
    {
        string airportName;
        double celsiusTemperature, elevation;


        if (String.IsNullOrEmpty(txtAirport.Text)) {
            MessageBox.Show("You did not enter a name for the airport.  Please enter a name for the airport.");
            return;
        } else
        {
            airportName = Convert.ToString(txtAirport.Text);
        }
        if (Double.TryParse(txtTemperature.Text, out celsiusTemperature))
        {
            if (celsiusTemperature > 50 || celsiusTemperature < -50)
            {
                MessageBox.Show("The value you entered for temperature is outside the acceptable range.  Please reenter the information");
                Application.Restart();
            }
        }
        else
        {
            MessageBox.Show("You did not enter a numeric value for the temperature.  Please enter a valid, i.e. numeric, value for the temperature.");
            return;
        }
        if (Double.TryParse(txtElevation.Text, out elevation))
        {
            if (elevation > 12000 || elevation < -300)
            {
                MessageBox.Show("The value you entered for elevation is outside the acceptable range.  Please reenter the information.");
                Application.Restart();
            }
        }
        else
        {
            MessageBox.Show("You did not enter a numeric value for the elevation.  Please enter a valid, i.e. numeric, value for the elevation.");
            return;
        }

        Airport myAirport = new Airport(airportName, celsiusTemperature, elevation);

        MessageBox.Show("The airport name is: " + myAirport.airportName(airportName) + Environment.NewLine + "The Celsius temperature is: " + myAirport.celsiusTemperature(celsiusTemperature)
            + Environment.NewLine + "The Fahrenheit temperature is: " + myAirport.temperatureInFahrenheit(celsiusTemperature) + Environment.NewLine + "The elevation is: " + myAirport.elevation(elevation));

    }

    private void button2_Click(object sender, EventArgs e)
    {
        Close();
    }

}

internal class Airport
{
    private string airportName1;
    private double celsiusTemperature1;
    private double elevation1;

    public Airport(string airportName1, double celsiusTemperature1, double elevation1)
    {
        this.airportName1 = airportName1;
        this.celsiusTemperature1 = celsiusTemperature1;
        this.elevation1 = elevation1;
    }

    public string airportName(string airportName1)
    {
        return airportName1;
    }

    public double celsiusTemperature(double celsiusTemperature1)
    {
       return celsiusTemperature1;
    }

    public double elevation(double elevation1)
    {
        return elevation1;
    }

    public double temperatureInFahrenheit(double celsiusTemperature1)
    {

        double fahrenheitTemperature = 0;

        fahrenheitTemperature = celsiusTemperature1 * (1.8) + 32;

        return fahrenheitTemperature;
    }

}
}

以下是如何简化Airport类的示例:

public class Program
{
    static void Main(string[] args)
    {
        var airport = new Airport { AirportName = "JFK", Temperature = 28.5 };

        Console.WriteLine(airport.ToString());
    }
}

public class Airport
{
    private string _airportName;

    private double _temperatureInCelsius;

    private double _temperatureInFahrenheit;

    public string AirportName
    {
        get
        {
            return _airportName;
        }
        set
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new Exception("You did not enter a name for the airport.  Please reenter the information.");
            }

            _airportName = value;
        }
    }

    public double Temperature
    {
        get
        {
            return _temperatureInCelsius;
        }
        set
        {
            if (value > 50 || value < -50)
            {
                throw new Exception("The value you entered for temperature is outside the acceptable range.  Please reenter the information");
            }

            _temperatureInCelsius = value;
            _temperatureInFahrenheit = _temperatureInCelsius *(1.8) + 32;
        }
    }
    public override string ToString()
    {
        return string.Format(
            "The airport name is: {0}\r\nThe Celsius temperature is: {1}\r\nThe Fahrenheit temperature is: {2}", _airportName, _temperatureInCelsius, _temperatureInFahrenheit);
    }        
}

请注意, AirportName setter会验证传递的机场名称(通过value ),如果无效,则将引发异常。

我将离开另一项属性-高程,作为锻炼的基础。

关于Message.Show你可以这样做:

Message.Show(airport.ToString());

ToString()方法返回一个描述机场的string

我的代码是一个建议,您不必完全使用它(即,您可能不希望从setter中引发异常。相反,您可以在创建Airport实例之前验证值。),但希望它能为您提供指导。

我认为,您应该通过以下方式重构代码:

  • 机场似乎是一个数据类。 因此,它不应该知道Form1的TextBox。 因此,请尝试将它们分开。

  • 为了方便访问,您应该考虑一下Airport类中字段的属性(或getter / setter方法)。

  • 您正在从机场班级中读取数据时正在检查数据。 如果您从不阅读或在内部使用过该怎么办? 因此,您应该将其分开。

  • 如果您估计错误,那么您将重新启动整个应用程序。 对于用户而言,这通常不是什么好事。 因此,请尝试显示错误并让用户进行一些更正。 然后再次检查,依此类推...

  • 如果“机场”是数据类,则必须具有“摄氏温度”和“华氏温度”的属性。 无论您具有什么样的内在表达。

我想先给出这些提示,而无需编写代码,因此您可以在考虑完整的解决方案之前自己考虑一下并尝试一下。 然后,如果您被困在某个地方,我(和其他人)将提供更多具体提示。

所以,祝你好运...

有很多方法可以区分不同的需求,因此我尝试给出一个想法。

首先,具有属性和内部验证的简单机场数据类(这意味着可能存在无效实例):

internal class Airport
{
    private string _airportName;
    private double _celsiusTemperature;
    private double _elevation;

    public Airport(string airportName, double celsiusTemperature, double elevation)
    {
        this._airportName = airportName;
        this._celsiusTemperature = celsiusTemperature;
        this._elevation = elevation;
    }

    public string AirportName
    {
        get
        {
            return _airportName;
        }
        set
        {
            _airportName = value;
        }
    }

    public double CelsiusTemperature
    {
        get
        {
            return _celsiusTemperature;
        }
        set
        {
            _celsiusTemperature = value;
        }
    }

    public double Elevation
    {
        get
        {
            return _elevation;
        }
        set
        {
            _elevation = value;
        }
    }

    public double TemperatureInFahrenheit
    {
        get
        {
            return _celsiusTemperature * (1.8) + 32.0;
        }
        set
        {
            if (value != 32.0)
            {
                _celsiusTemperature = (value - 32.0) / (1.8);
            }
            else
            {
                _celsiusTemperature = 0.0;
            }
        }
    }

    public bool IsValid(out string errorMessage)
    {
        bool result = false;

        bool ok = true;
        errorMessage = "";

        if (String.IsNullOrEmpty(_airportName))
        {
            ok = false;
            errorMessage = "You did not enter a name for the airport.";
        }

        if (_celsiusTemperature > 50 || _celsiusTemperature < -50)
        {
            ok = false;
            errorMessage = "The value you entered for temperature is outside the acceptable range.";
        }

        if (_elevation > 12000 || _elevation < -300)
        {
            ok = false;
            errorMessage = "The value you entered for elevation is outside the acceptable range.";
        }

        result = ok;

        return result;
    }
}

请注意,华氏温度是基于摄氏温度的计算值。 反之亦然。

另请注意验证。 机场类接受所有值,仅定义字段的类型。 它进行语义检查(业务逻辑)。

现在,如何使用它:

private void button1_Click(object sender, EventArgs e)
{
    string airportName;
    double celsiusTemperature;
    double elevation;

    // Get data from controls and do syntactic checks
    bool ok = true;
    airportName = txtAirport.Text;

    ok = Double.TryParse(txtTemperature.Text, out celsiusTemperature);
    if (!ok)
    {
        // Error
        MessageBox.Show("The value you entered for temperature is not a number!", "Error");
    }

    ok = Double.TryParse(txtElevation.Text, out elevation);
    if (!ok)
    {
        // Error
        MessageBox.Show("The value you entered for elevation is not a number!", "Error");
    }


    if (ok)
    {
        // Create the instance of the data class and do semantic checks
        Airport myAirport = new Airport(airportName, celsiusTemperature, elevation);
        string errorMessage;
        if (!myAirport.IsValid(out errorMessage))
        {
            // Error
            MessageBox.Show(errorMessage + " Please reenter the information", "Error");
        }
        else
        {
            // Ok, data is valid. Continue normal work...
            MessageBox.Show("The airport name is: " + myAirport.AirportName + Environment.NewLine +
                            "The Celsius temperature is: " + myAirport.CelsiusTemperature + Environment.NewLine +
                            "The Fahrenheit temperature is: " + myAirport.TemperatureInFahrenheit + Environment.NewLine +
                            "The elevation is: " + myAirport.Elevation);
        }
    }

您从控件获取数据并进行语法检查。 如果一切正常,则让类自己进行语义检查。 在这里它将给出一个字符串作为消息详细信息,但是许多其他方法都是可以通过的。

因此,最后,如果发生语法错误,用户将收到一条消息并可以继续。 如果发生语义错误,则用户会收到一条消息并可以继续。 如果一切正常,则可以操作有效数据。

希望这可以帮助...

暂无
暂无

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

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