Can't modify the return value of 'expression' because it is not a variable? (无法修改XX的返回值,因为它不是一个变量)

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.

原文地址:https://www.cnblogs.com/zwffff/p/2077770.html