C#使用列表<T>或if语句等

问题描述 投票:0回答:2
当在C#中使用structs - 使用if语句或否则?

private struct ExampleStruct { public int a; public ExampleStruct() { a = 1; } } List<ExampleStruct> exampleList = new List<ExampleStruct>(); ExampleStruct newExampleStruct = new ExampleStruc(); exampleList.Add(newExampleStruct); for(int i = 0; i < exampleList.Count; i++) { if(exampleList[i].a == 1)//Does this cause a copy of the struct? { Console.WriteLine("Struct value has been compared."); } }

我尝试研究C#的官方原始资料以及我能找到的其他任何内容,但我找不到有关在列表中使用结构的明确答案。
    

导致结构副本的事物是索引器
c# list struct
2个回答
0
投票
,即

exampleList[i] <=== this bit

但是,如果您绝对需要使用
CollectionsMarshal.AsSpan

,您可以解决这个问题。这通常仅适用于large
large
结构和非变换列表。

注意,可变的struct是一个坏主意,可能会引起很多问题。做

ExampleStruct
readonly struct

是个好主意

是的,是的,因为结构本身(与引用相反)作为列表索引运算符的输出返回。
这不是特定于列表或索引运算符的特定(这可能就是为什么您找不到该特定情况的文档),但是对于返回
struct
值的
Yany
函数是正确的。

下一个问题是 - 这是一个问题吗? 您通过返回结构而不是对对象的引用来期待什么问题?如果您认为这是一个问题,那么为什么首先将其定义为

0
投票
呢?使用结构所需的好处是否超过传递数据而不是参考的缺点?

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.