在 if 语句中调用变量并在 else if 语句中使用 C#

时间:2021-04-12 02:39:56

标签: c# livechat

我是 C# 的新手。下面的代码显示有一个 if else 语句,该语句实际上是关于我有 3 个文本框,其中 2 个文本框在我点击图表的点时会得到数据,另一个文本框会计算两点之间的差异。现在我无法让 x1 和 y1 与我一起减去 x2 和 y2。我在 else if 语句中得到的 x1 和 y1 的值为 0。

下面还有其他代码,但我不会在这里包含它,因为它不相关。

private void MyChart_DataClick(object sender, ChartPoint point)
{
    double x1 = 0;
    double x2 = 0;
    double y1 = 0;
    double y2 = 0;
    double differenceX = 0;
    double differenceY = 0;
    double absoluteVX = 0;
    double absoluteVY = 0;
    
    if (String.IsNullOrEmpty(txbCoordinate1.Text) && String.IsNullOrEmpty(txbCoordinate2.Text))
    {
        txbCoordinate1.Text = "X-axis " + point.X.ToString("0.00 umum") + "\n" + "Y-axis " + point.Y.ToString("0.00 um");
        x1 = point.X;
        y1 = point.Y;
    }
    else if (!String.IsNullOrEmpty(txbCoordinate1.Text) && String.IsNullOrEmpty(txbCoordinate2.Text))
    {
        txbCoordinate2.Text = "X-axis " + point.X.ToString("0.00 um") + "\n" + "Y-axis " + point.Y.ToString("0.00 um");
        x2 = point.X;
        y2 = point.Y;
        differenceX = x1 - x2;
        differenceY = y1 - y2;
        absoluteVX = Math.Abs(differenceX);
        absoluteVY = Math.Abs(differenceY);
        txbDifference.Text = "X-axis " + x1.ToString("0.00 um") + "\n" + "Y-axis " + absoluteVY.ToString("0.00 um");
        
    }
    else if (!String.IsNullOrEmpty(txbCoordinate1.Text) && !String.IsNullOrEmpty(txbCoordinate2.Text))
    {
        txbCoordinate1.Text = "X-axis " + point.X.ToString("0.00 um") + "\n" + "Y-axis " + point.Y.ToString("0.00 um");
        txbCoordinate2.Text = string.Empty;
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您的问题是您使用了每次调用方法时都会创建的局部变量。

您需要将它们移到方法之外:

double x1 = 0;
double x2 = 0;
double y1 = 0;
double y2 = 0;
double differenceX = 0;
double differenceY = 0;
double absoluteVX = 0;
double absoluteVY = 0;

private void MyChart_DataClick(object sender, ChartPoint point)
{