csgashine

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
    Struct is value type. When it used as a parameter of Functions, it is passed by values which is the copy of the struct. When you return t the calling function, the values are unchanged. 
    While you change thedeclaration with class,and the values will be changed. Thus, when the values are changed in myFunc( ), they are changed on the actual object back in Main().

     Because loc1 is a struct (not a class), it is created on the stack. Thus, in Example  when the new operator is called:

   Location loc1 = new Location(200,300); 


the resulting Location object is created on the stack.
The new operator calls the Location constructor. However,unlike with a class, it
is possible to create a struct without using new at all.
 
No initialization

 

You can't initialize an instance field in a struct. Thus, it is illegal to write:

private int xVal = 50;
private int yVal = 100;

though that would have been fine had this been a class





































 
Example:

namespace CreatingAStruct {















public struct Location { private int xVal; private int yVal; public Location( int xCoordinate, int yCoordinate ) { xVal = xCoordinate; yVal = yCoordinate; } public int x { get { return xVal; } set { xVal = value; } } public int y { get { return yVal; } set { yVal = value; } } public override string ToString( ) { return ( String.Format( "{0}, {1}", xVal, yVal ) ); } } public class Tester { public void myFunc( Location loc ) { loc.x = 50; loc.y = 100; Console.WriteLine( "In MyFunc loc: {0}", loc ); } static void Main( ) { Location loc1 = new Location( 200, 300 ); Console.WriteLine( "Loc1 location: {0}", loc1 ); Tester t = new Tester( ); t.myFunc( loc1 ); Console.WriteLine( "Loc1 location: {0}", loc1 ); } } }



2. Create a struct without new



posted on 2006-01-22 21:58  asp-shine  阅读(292)  评论(0编辑  收藏  举报