Address: http://blog.csdn.net/onlyou930/article/details/5568319
Compilation error cs1612
Cannot modify the return value'Expression'Because it is not a variable
The Return Value of "expression" cannot be modified because it is not a variable.
The most common error is:
Anobject. anstruct. vaule = xxx;
Consider the following: Program : No problem at first glance. In fact, it cannot be compiled.
Using system;
Using system. Collections. Generic;
Using system. text;
Namespace consoleapplication1
{
Public struct rectangle
{
Private int _ width;
Private int _ height;
Public int width
{
Get {return _ width ;}
Set {_ width = value ;}
}
Public int height
{
Get {return _ height ;}
Set {_ Height = value ;}
}
Public rectangle (INT width, int height)
{
This. _ width = width;
This. _ Height = height;
}
}
Public class draw
{
Private rectangle _ rect = new rectangle (0, 0 );
Public rectangle myrect
{
Get {return _ rect ;}
Set {_ rect = value ;}
}
Public draw (){}
Public draw (INT mapwidth, int mapheight)
{
_ Rect = new rectangle (mapwidth, mapheight );
}
}
Class Program
{
Static void main (string [] ARGs)
{
Draw draw = new draw ();
Draw. myrect. width = 20; // compilation Error
Draw. myrect. Height = 12; "=" Compilation error"
}
}
}
Draw is a reference type, and myrect is a struct, that is, a value type. Draw. myrect will call
Public rectangle myrect
{
Get {return _ rect ;}
}
The value type is passed by value by default, and a temporary local copy of _ rect on the stack is returned. We call it temp_rect for the moment,
Draw. myrect. width = 20 is equivalent to temp_rect.width = 20;
Therefore, it cannot be reflected in draw even if it can be modified. myrect itself (I .e. _ rect), that is, this is a meaningless operation, so the compiler prohibits such operations from the source.
Solution:
1) Replace struct with class, so that myrect becomes an object (reference type), draw. myrect will return the actual address of _ rect on the stack, and the modification will also reflect the actual object
2) If you have to use struct, you need to set an intermediate variable:
Draw draw = new draw ();
Rectangle temprect = new rectangle ();
Temprect. width = 20;
Temprect. Height = 12;
Draw. myrect = temprect;
This replaces the entire _ rect attribute of the draw object.
Refer:
Msdn: Compiler error cs1612 (compiler error cs1612 (C #))
Now, you can see that Chinese is much inferior to the original English version.
C #-struct in a class .. can not access properties of the struct
Additional reading:
CLR generics limitation-modifying values in situ in a container
C #: List of struct