我什至不知道该如何表达这个问题。我将一些CustomStruct对象作为参数传递给类方法,并将它们存储在List中。我想知道的是,如果找到同等的实例,是否可以向CustomStruct的特定实例添加多个引用,并且效率更高。

这是一个虚拟/示例结构:

public struct CustomStruct
{
    readonly int _x;
    readonly int _y;
    readonly int _w;
    readonly int _h;
    readonly Enum _e;
}


使用以下方法,可以传递一个,两个或三个CustomStruct对象作为参数。在最终方法(采用三个参数)中,第3个甚至第2个可能具有与第一个相同的值。

List<CustomStruct> _list;

public void AddBackground(CustomStruct normal)
{
    AddBackground(normal, normal, normal);
}

public void AddBackground(CustomStruct normal, CustomStruct hover)
{
    AddBackground(normal, hover, hover);
}

public void AddBackground(CustomStruct normal, CustomStruct hover, CustomStruct active)
{
    _list = new List<CustomStruct>(3);
    _list.Add(normal);
    _list.Add(hover);
    _list.Add(active);
}


按照目前的方法,我相信它将创建CustomStruct对象的新实例,然后将每个实例的引用添加到List。

据我了解,如果我改为检查normal和hover之间的相等性,然后(如果相等)再次插入normal代替hover,则在该方法完成后,hover将丢失所有引用并最终被垃圾回收,而normal将有两个引用在列表中。主动也可以这样做。

那会更好,对吧? CustomStruct是一个ValueType,因此一个实例将保留在堆栈上,而三个List引用将指向该实例。列表的总大小不是由所包含的对象类型决定的,而是由其容量决定的。通过消除“重复的” CustomStuct对象,可以清除它们。

将CustomStruct对象传递给这些方法时,每次都会创建新的实例。将这些结构添加到列表时,是否会复制另一个副本?例如,如果我仅传递一个CustomStruct,则AddBackground(normal)创建原始变量的副本,然后将其传递3次到Addbackground(normal,hover,active)。在这种方法中,由原始副本制作了三个副本。当使用Add()将三个局部变量添加到列表时,是否在Add()内部创建了其他副本,这是否违反了前面提到的任何相等性检查的目的?

有没有更好的方法来解决这个问题?应该将结构作为对方法的引用来解决吗?

我在这里想念什么吗?

最佳答案

您在同一行中谈论垃圾收集和结构,这没有任何意义。最终,每次查看结构​​时,它都有可能复制自身。如果要重复使用相同的引用,则需要一个类,或者将结构包装在一个类中(装箱;内置或手动)。

您的代码中实际发生的是:

_list.Add(normal); // a **copy** of normal is set into the list
_list.Add(hover); // a **copy** of hover is set into the list
_list.Add(active); // a **copy** of active is set into the list


当您考虑时,哪一个在空间方面等同于:

_list.Add(normal); // a **copy** of normal is set into the list
_list.Add(normal); // a **copy** of normal is set into the list
_list.Add(normal); // a **copy** of normal is set into the list


请注意,副本不会进入堆栈(struct = stack是一个常见的神话)。数据进入堆中的数组(在List<>内部)。通过引用传递该结构对Add的行为没有任何影响(它只是避免将结构传递给此方法时复制该结构,但是内存复制速度很快)。

07-24 09:44
查看更多