Types and Initialization

Types are allowed to provided a distinguished method that is called when the type is first initialized. This type initializer is simply a static method with a well-known name(.cctor). A type can have at most one type initializer, and it must take no parameters and return no value. It is called automatically by CLR. The following shows a type initializer in C#:

namespace EssentialNet

{

    public class Customer

    {

        public static string name;

 

        static Customer()

        {

            name = "xiech2";

        }

    }

}

If a single C# type have both an explicit type initializer method and static field declarations with initializer expressions, .cctor method will begin with field initializers(in order of declaration), followed by the body of the explicit typer initializer method. Consider the following C# type definiation:

namespace EssentialNet

{

    public class Customer

    {

        public static string name;

 

        public static string id = "C1";

 

        public static string code = "XIECH2";

 

        static Customer()

        {

            name = "xiech2";

        }

    }

}

The fields will be initialized in the following order:id,code,name.

 

There is another distinguished method that CLR will call automatically each time an instance of the type is allocated. It is called a constructor and must have the distinguished name .ctor. The C# compiler will inject any non-static field initialization expressions in to the generated .ctor before the explicit method body. Consider the following C# type definition:

namespace EssentialNet

{

    public class Customer

    {

        public static string name;

 

        public static string id = "C1";

 

        public static string code = "XIECH2";

 

        public long t1 = DateTime.Now.Ticks;

 

        public long t2 = DateTime.Now.Ticks;

 

        public long t3;

 

         static Customer()

        {

            name = "xiech2";

        }

 

        public Customer()

        {

            t3 = DateTime.Now.Ticks;

        }

 

       

    }

}

The fields will be initialized in the following order:t1,t2,t3.

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值