要点摘要:

  

The Differences  between classes and structs

  • classes are reference types stored in the heap ; structs are value types ,they are stored either in the stack or inline and have the same lifetime restrictions as the simple data types.
  •  structs do not support inheritance
  • there are some differents in the way constructors work for structs .In particular,the compiler always supplies a default no-paramater constructors,which you are not permittedto replace.
  • With a struct ,you can specify how the fields are be laid out in memory.

Properties

  1) read-only and write-only properties:

       create a read-only property by simply omitting the set  accessor from the property definition;

      create a write-only property by omitting the get accessor.

  2)access modifers for properties:

      e.g. (get is public and set is private) 

    public string Name
    {
        get
        {
            return _name;
        }
        private set 
        {
            _name = value;
        }
    }

3) auto implimented properties
public string ForeName {get; set;}
public string ForeName {get;} 
public string ForeName {get; private set;}

 

Static Constructors

a static no - parameter constructor for a class will be executed only once, as opposed to the constructors written so far, which are
instance constructors that are executed whenever an object of that class is created.

e.g.
 public MyClass

{

  static MyClass()

{

//initialization code

}

//rest of the class definition

}

Notice:

i) the static constructor does not have any access modifiers. It ’ s never called by any other C# code, but always by the .NET runtime when the class is loaded

ii) the static constructor can never take any parameters, and there can be only one static constructor for a class.

iii) a static constructor can access only static members, not instance members, of the class


ReadOnly Fields

constants don ’ t necessarily meet all requirements.On occasion, you may have some variable whose value shouldn ’ t be changed, but where the value is not known until runtime. C# provides another type of variable that is useful in this scenario: the readonly field

The rule is that you can assign values to a readonly field inside a constructor, but not anywhere else. It ’ s also possible for a readonly field to be an instance rather than a static field, having a different value for each instance of a class.This means that, unlike a const field, if you want a readonly field to be static, you have to declare it as such.

 

 

 

 

posted on 2010-05-23 18:17  佐伊凡  阅读(368)  评论(0编辑  收藏  举报