如何将当前 var 分配给 else 语句以便能够比较 var 值然后保存它以获得结果?

How can I assign a current var to else statement to be able to compare the var value and then save it to get a result?

我有一个 If Else 语句来获取距离当前站点最近的站点,这意味着第一个最近的站点为空(不存在),第二个站点是根据第一个站点的最小距离计算的。在其他部分,我使用 Math.Min 将当前站点的距离与已知的最小距离进行比较。但是,我缺少存储结果并在 Else 语句中分配当前站。我问题的地方是第14和15行。

class City : ICity
    {
        private List<Company> _companies;
        private List<Line> _lines;
        private List<Station> _stations;
        internal City(string name)
        {
            this.Name = name;
            _companies = new List<Company>();
            _lines = new List<Line>();
            _stations = new List<Station>();
        }
        public string Name{get;}
        public ILine AddLine(string name){...} 
        public IStation AddStation(string name, int x, int y){...}

        public IStation FindNearestStation(int x, int y)
        {
            int ? minDist = null;
            Station minStation=null;
            foreach (var station in _stations)
            {
                int dis = GetDistancebtween(x1: station.X, y1: station.Y, x2: x, y2: y);
                if (!minDist.HasValue || dis < minDist.Value)
                {
                    minDist = dis;
                    minStation = station;
                }
            }
            return minStation;            
        }

        private int GetDistancebtween(int x1, int y1, int x2, int y2)
        {
            return (x1 - x2) ^ 2 + (y1 - y2) ^ 2; 

        }            
}

单元测试在第 10 行中断。

public void city_returns_effectively_the_closest_station()
{
    ICity c = CityFactory.CreateCity("Paris");

    IStation s = c.AddStation("Opera", 0, 0);
    IStation s1 = c.AddStation("Chatelet", 10, 10);

    c.FindNearestStation(-10, -10).Should().BeSameAs(s);
    //test does not pass in this position
    c.FindNearestStation(10, 10).Should().BeSameAs(s1);
    c.FindNearestStation(15, 15).Should().BeSameAs(s1);
}

如果您更改了 minDist 值,那么您也应该更改 minStation 值。在 else 块中使用简单的 if 而不是 Math.Min 应该可以解决问题。

....
else
{
    if(dis < minDist.Value)
    {
        minDist = dis;
        minStation = station;
    }
}

这会导致在不使用 else 块的情况下进行进一步的更改

foreach (var station in _stations)
{
    var dis = GetDistancebtween(x1: x, y1: y, x2: station.X, y2: station.Y);
    if(!minDist.HasValue || dis < minDist.Value)
    {
        minDist = dis;
        minStation = station;
    }
}