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;
  • 相关阅读:
    均匀采样单位圆
    3Sum
    查看SQL语句在SQL Server上的执行时间
    ASP.NET页面请求处理
    原型模式
    ASP.NET页面错误处理
    电子商务推荐位商品模型设计
    HttpModule与HttpHandler使用
    装饰者模式
    ASP.NET编程模型
  • 原文地址:https://www.cnblogs.com/ring1992/p/6385105.html
Copyright © 2011-2022 走看看