悟道人生

渴望闲云野鹤的生活,面对自然,鸟鸣虫唱,星辰为伴,没有拘束,没有苦恼,有的只是神仙般的生活

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::

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.

posted on 2011-06-10 16:33  凌风有约  阅读(1127)  评论(0编辑  收藏  举报