You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中List<T>内的struct在IF语句等场景下会被复制吗?

在List中访问struct成员时是否会创建副本?

是的,你代码里if(exampleList[i].a == 1)这一行会创建该struct的副本。

原因很简单:C#里struct是值类型,List的索引器在返回值类型元素时,会返回该元素的完整值副本——这是值类型的默认行为。哪怕你只是要读取它的成员a,也会先把整个struct拷贝一份,再从这个副本上获取a的值。

补充说明

  • 如果你的struct体积很小(比如示例里只有一个int字段),这种拷贝的性能开销几乎可以忽略,不用特意优化。
  • 但如果是包含大量字段的大型struct,频繁通过索引器访问成员会累积不必要的性能消耗。这时可以先把struct拷贝到局部变量,再访问成员,这样只需要拷贝一次:
    for(int i = 0; i < exampleList.Count; i++)
    {
        ExampleStruct temp = exampleList[i]; // 仅一次拷贝
        if(temp.a == 1)
        {
            Console.WriteLine("Struct value has been compared.");
        }
    }
    
  • 另外,如果场景允许,也可以考虑把struct改成class(引用类型),这样访问List元素时不会产生拷贝,但要注意引用类型的语义和内存管理和值类型的差异。

修正后的示例代码

private struct ExampleStruct
{
    public int a;

    public ExampleStruct()
    {
        a = 1;
    }
}

List<ExampleStruct> exampleList = new List<ExampleStruct>();
ExampleStruct newExampleStruct = new ExampleStruct();
exampleList.Add(newExampleStruct);

for(int i = 0; i < exampleList.Count; i++)
{
    if(exampleList[i].a == 1)// 此处会创建struct的副本
    {
        Console.WriteLine("Struct value has been compared.");
    }
}

内容的提问来源于stack exchange,提问作者OrinVexler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:55:04