Can’t modify the return value of ‘expression’ because it is not a variable? (無法修改X

來源:互聯網
上載者:User

Today, I met an error which sent a message like 'Can't modify the return value,because it is not a variable'.

Now, let us see how this problem happens?

First, I had defined a struct named SeqString.

public struct SeqString{private char[] _data;private int _length;public SeqString(int size){_data=new char[size];_length=0;}/// <summary>/// The string data/// </summary>public char[] Data{get{return _data;}}/// <summary>/// The length of the string/// </summary>public int Length{set{_length=value;}get{return _length;}}/// <summary>/// The total size of the array /// </summary>public int Size{get{return _data.Length;}}}

Second, I had created an instance of this struct, also defined a property to return the instance.

/// <summary>/// Description of SequenceString./// </summary>public class SequenceString{SeqString _seq;public SequenceString(int size){_seq=new SeqString(size);}public SeqString String{get{return _seq;}}}

At last, in the main function, I created an instance 'sequenceString' of SequenceString class. and when I used the code 'sequenceString.String.Length=3' to set the property 'Length' of the struct instance. There occurs the error like the title descripts.

public static void Main(string[] args){SequenceString sequenceString=new SequenceString(100);sequenceString.String.Length=3;}

Now, let us find why this problem happens?

We all know struct is a value type, and is stored on the stack, and although we can set the value to the struct, but it doesn't reflect back into the original property. So when we try to do this, the compiler will refuse to compile.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.