当前位置:网站首页>In C#, why can't I modify the member of a value type instance in a foreach loop?
In C#, why can't I modify the member of a value type instance in a foreach loop?
2022-07-05 23:30:00 【Superior virtue and weak water】
problem :
I know that value types should be immutable, but that's just a suggestion, not a rule, right? I know that the value type should be immutable , But this is just a suggestion , Not the rules , Right ?So why can't I do something like this: Then why can't I do such a thing :
struct MyStruct{ public string Name { get; set; }} public class Program{ static void Main(string[] args) { MyStruct[] array = new MyStruct[] { new MyStruct { Name = "1" }, new MyStruct { Name = "2" } }; foreach (var item in array) { item.Name = "3"; } //for (int i = 0; i < array.Length; i++) //{ // array[i].Name = "3"; //} Console.ReadLine(); }}
The foreach loop in the code doesn't compile while the commented for loop works fine. In code foreach Loop cannot compile , And annotated for The cycle works normally .The error message: error message :
Cannot modify members of 'item' because it is a 'foreach iteration variable' Can't modify “item” Members of , Because it is “foreach Iterative variable ”
Why is that? Why is that ?
Solution :
Reference resources : https://stackoom.com/en/question/Ni0P边栏推荐
- MySQL delete uniqueness constraint unique
- Idea connects to MySQL, and it is convenient to paste the URL of the configuration file directly
- 98. Verify the binary search tree ●●
- TVS管和ESD管的技术指标和选型指南-嘉立创推荐
- CIS基准测试工具kube-bench使用
- Comparison between webgl and webgpu [3] - vertex buffer
- LeetCode——Add Binary
- Creative mode 1 - single case mode
- MySQL (1) -- related concepts, SQL classification, and simple operations
- 进击的技术er——自动化
猜你喜欢
Debian 10 installation configuration
2:第一章:认识JVM规范1:JVM简介;
Practice of concurrent search
Data analysis - Thinking foreshadowing
orgchart. JS organization chart, presenting structural data in an elegant way
Pyqt control part (I)
February 13, 2022-4-symmetric binary tree
基于脉冲神经网络的物体检测
两数之和、三数之和(排序+双指针)
2: Chapter 1: understanding JVM specification 1: introduction to JVM;
随机推荐
February 13, 2022 -5- maximum depth of binary tree
From the perspective of quantitative genetics, why do you get the bride price when you get married
Difference between out of band and in band
Use of shell:for loop
(4) UART application design and simulation verification 2 - RX module design (stateless machine)
White hat talks about web security after reading 2
Huawei simulator ENSP - hcip - MPLS experiment
基于脉冲神经网络的物体检测
How to design API return code (error code)?
Using LNMP to build WordPress sites
Three. JS VR house viewing
判斷二叉樹是否為完全二叉樹
(4)UART应用设计及仿真验证2 —— RX模块设计(无状态机)
UVA11294-Wedding(2-SAT)
派对的最大快乐值
How to enable relationship view in phpMyAdmin - how to enable relationship view in phpMyAdmin
进击的技术er——自动化
yate. conf
Golang code checking tool
TVS管和ESD管的技術指標和選型指南-嘉立創推薦