gpt4 book ai didi

c# - 在 C# 中修改对象

转载 作者:行者123 更新时间:2023-12-02 22:04:51 25 4
gpt4 key购买 nike

(如果你能想到更好的标题,请告诉我。)

我正在研究路线优化程序。我从路线需要包括的点列表开始。我的第一步是创建所有可能路线(排列)的列表。然后我会删除所有可能的路线(例如,如果一个站点必须在另一个站点之前)。完成后,我会计算每条可能 route 每个点之间的距离和时间。每个点都是一个对象 (TPoint),所有距离和时间值都存储在一个名为 TData 的单独类中,该类存储在 TPoint 的每个实例中。我的问题是:当我尝试在第一站更新 TData 时,在第一条可能的 route ,它将更新每条可能 route 相同 TPoint 的 TData。这是因为类是引用类型,并且存储在堆上。我正在寻找一种允许我在每个 TPoint 上存储 TData 的解决方案。

下面是一些示例代码(下面的代码演示了当我修改一个对象(TPoint)时,我实际上只是使用引用来修改堆上的对象):

主要

// Let's create a list of points we need to hit.
List<TPoint> lstInitial = new List<TPoint>();
lstInitial.Add(new TPoint("A", new TData(-1, -1)));
lstInitial.Add(new TPoint("B", new TData(-1, -1)));
lstInitial.Add(new TPoint("C", new TData(-1, -1)));

// Now let's get all possible routes
IList<IList<TPoint>> lstPermutations = Permutations(lstInitial);

// Let's write these values to the first point, in the first possible route.
lstPermutations[0][0].oTData.distance = 10;
lstPermutations[0][0].oTData.minutes = 20;

foreach (IList<TPoint> perm in lstPermutations)
{
foreach (TPoint p in perm)
{
Response.Write(p.id + "|" + p.oTData.distance + "|" + p.oTData.minutes);
Response.Write(" ");
}
Response.Write("<br />");
}

置换函数

// Get permutations
private static IList<IList<T>> Permutations<T>(IList<T> list)
{
List<IList<T>> perms = new List<IList<T>>();

// If the list is empty, return an empty list.
if (list.Count == 0)
{
return perms;
}

// This is a loop method to get the factorial of an integer
int factorial = 1;
for (int i = 2; i <= list.Count; i++)
{
// shortcut for: factorial = factorial * i;
factorial *= i;
}

for (int v = 0; v < factorial; v++)
{
//List<T> s = new List<T>(list);
List<T> s = new List<T>(list);

int k = v;
for (int j = 2; j <= list.Count; j++)
{
int other = (k % j);
T temp = s[j - 1];
s[j - 1] = s[other];
s[other] = temp;

k = k / j;
}
perms.Add(s);
}

return perms;
}

public class TPoint
{
public TPoint(string _id, TData _oTData)
{
id = _id;
oTData = _oTData;
}

public string id { get; set; }
public int someInt { get; set; }
public TData oTData { get; set; }
}

public class TData
{
public TData(int _distance, int _minutes)
{
distance = _distance;
minutes = _minutes;
}

public int distance { get; set; }
public int minutes { get; set; }
}

好像我已经设法把自己逼到了一个角落。我可以想到一些解决方案,但它们看起来很乱,所以我想我应该就此问题请教专家。

编辑

谁能想到为什么这不是一个好主意?

取而代之的是,它修改堆上的对象(并影响每个可能路径中的每个点):

lstPermutations[0][0].oTData.distance = 10;
lstPermutations[0][0].oTData.minutes = 20;

使用这个,它只是创建一个类的新实例:

TPoint oTPoint = new TPoint(lstPermutations[0][0].id, new TData(10, 20));
lstPermutations[0][0] = oTPoint;

最佳答案

如果您将 TData 设为结构体,那么它将按值而不是按引用进行复制。否则,您将不得不制作一个复制值的浅表克隆。

关于c# - 在 C# 中修改对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16308205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com