zoukankan      html  css  js  c++  java
  • List<> of struct with property. Cannot change value of property. why?

    这个返回如下错误:"Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this[int]' because it is not a variable"

    class Program
    {
        private struct MyStruct
        {
            private int myVar;
            public int MyProperty
            {
                get { return myVar; }
                set { myVar = value; }
            }
        }
    
        private static List<MyStructlist> list = new List<MyStruct>();
    
        private static void Main(string[] args)
        {
            MyStruct x = new MyStruct();
            x.MyProperty = 45;
            list.Add(x);
            list[0].MyProperty = 45; // <----------- ERROR HERE
        }
    }

    The [] operator on a list is, in fact, a function, so the value stored at that location in the list is returned as a function result,on the stack.

    This doesn't cause problems for reference types, because usually you want to change some property of the reference type, so the fact that you get a copy of the reference in the list (not the actual reference that is in the list) doesn't cause problems.

    However, for value types exactly the same thing happens, and it does cause problems: the value is copied from the list onto the stack and returned as a function result. Modifying the returned value, of course, has no effect on the contents of the list. The compiler wisely catches this.

    //You need to do this:

    MyStruct y = list[0]; y.MyProperty = 45; list[0] = y;
  • 相关阅读:
    c#委托总结
    架构研究一(autofac 注册路由 )
    Fedora20 和ubuntu 14.04 chrome标签中文乱码
    Fedora20 编译安装qemu-system
    NFS安装配置
    Mysql自动备份脚本
    Mysql性能调优(my.cnf参数篇)
    Mysql性能基本测试
    mysql编译安装主从复制
    Mysql 配置参数详解以及优化配置
  • 原文地址:https://www.cnblogs.com/ring1992/p/6385105.html
Copyright © 2011-2022 走看看