Professional C# 学习笔记(三 c#对象和类型)

要点摘要:

  

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.

 

 

 

 

转载于:https://www.cnblogs.com/fightLonely/archive/2010/05/23/1742137.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值