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

Passing an argument to a method in C#

所以,这个程序可以正常运行,但我认为代码不是很好"clean,",所以我正在寻找建议。我遇到的两个大问题:

  1. 对于方法 public double temperatureInFahrenheit,我想将参数 celsiusTemperature 传递给函数,而不必重新声明变量,将其从文本转换为 double 等。每当我尝试调用函数 myAirport.temperatureInFahrenheit 时,我都会在 MessageBox.Show 中遇到错误(我不记得具体是什么错误,所以如果是这样,我将不得不重新编码需要)。关于我可以做些什么来完成这项工作有什么想法吗?

  2. public 部分 class Form1 中的 MessageBox.Show 对我来说似乎是乱码。我想做的是在内部 class 机场编写一个方法,将必要的参数传递给该方法,然后执行类似 MessageBox.Show(myAirport.message()) 的操作,但我假设如果我尝试,我会得到与 1 相同的错误。有什么想法吗?

同样,代码是完全可用的,可以工作并满足要求的规范,但我不喜欢只有功能代码,我喜欢 "pretty." 注意:我没有评论对于任何方法、变量等。我现在就把它们放进去,但我想我会先尝试获得一些反馈。

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 class:

的示例
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()方法return一个string

我的代码是一个建议,您不必完全使用它(即您可能不喜欢从 setter 中抛出异常。相反,您可以在创建 [=11 之前验证这些值=] 实例。),但希望它能指导你。

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

  • 机场好像是个数据class。所以它不应该知道 Form1 的 TextBox。所以,试着把它们分开。

  • 为了便于访问,您应该为您在机场的字段考虑属性(或getter/setter方法)class。

  • 你在机场外读数据的时候正在检查数据class。如果您以前从未阅读过或在内部使用过怎么办?所以,你应该把它分开。

  • 如果您估计错误,您将重新启动整个应用程序。这对用户来说通常不是一件好事。所以尽量显示错误并让用户做一些更正。并再次检查,依此类推...

  • 如果 Airport 是数据 class,那么您可以拥有摄氏度和华氏度的属性。不管你在内部有什么代表。

我想先在没有代码的情况下给出这些提示,这样你就可以在看完整的解决方案之前自己思考和尝试。然后,如果你卡在某个地方,我(和其他人)会给出更具体的提示。

所以,祝你好运...

有很多方法可以区分不同的需求,所以我试着给出思路。

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

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;
    }
}

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

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

现在,如何使用它:

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);
        }
    }

您从控件中获取数据并进行语法检查。如果一切正常,你让 class 自己做语义检查。这里会给出一个字符串作为消息的详细信息,但是很多其他的方式都是可以的。

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

希望这对您有所帮助...