effective hierarchy(二)之 函数合辑(2)

 

介绍:

本节我们来看看另外一种封装,构建件。构建件作为类的入口,用于描述类在初始化时的状态,本质上是一种具有系统约定的函数。

 

1.构建件,类进行实化(实例化)对象和定义数据类型值时(new(msil:newobj命令))调用的特殊方法。即,用构建件来初始化(一个类)。

 

(1)语法为:

        <class> <object> = new <class>(constructor arguments){constructor body}

 (2)缺省构建件

         每个类都有缺省的构建件,一般情况下,被隐式调用。

 

2.静态构建件

 静态成员是存在于应用程序全生命周期内的唯一copy,但在访问序列中具有较高的优先级,甚至优先于类的实化,它是真正的系统级和应用级“模板”--静态成员是在载入应用程序(该应用包含成员所在类)时创建!故该成员能够在类的实化之前就被访问。(另注意,静态的优先级在应用上远高于实例的优先级,即,在需要实化的地方,当然可以使用静态成员来实化。)

 

   静态构建件具有静态成员的特性,在互操作环境内,也被称做(成员所在类)“类构建件”;而,非静态构建件被称为“对象构建件”(实例化构建件)。类构建件与对象构建件在语法上仅是访问符有所不同,但可以在一个类内同时存在。

//静态构建件,示例.
using System;
class BaseStatic
{
    public static int i;
    static BaseStatic()
    {
        i = 100;
        Console.WriteLine("BaseStatic Constructor");
        Console.WriteLine("i value is " + i);
    }
}
class StaticCons
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Static Constructor");
        Console.WriteLine("------------------");
        BaseStatic oBaseStatic = new BaseStatic();
    }
}

  

一、基础 

 

1.基本特征

(1)用于捕获参数(capture parameters)且初始化值,确保一个类的对象在使用前被正确初始化。尽量不用于复杂逻辑处理;

(2)它是系统级“元素”;

(3)构建件的名称与所在类的类名称同名;

(4)构建件没有返回值,也没有返回类型--一个不需要结果的“过程元素”;

(5)构建件可被重载(overloadded),这点与方法相同,多态性(相同的方法名不同的参数)同样适用于构建件。发生这种情况时,称之为重载的构建件。

 

2.静态构建件

(1)不能有参数,不能有访问修饰符,故一个类只允许有一个静态构建件;

(2)只能用于对类的静态成员的处理!不允许处理实化成员,否则会引发“非静态的方法、字段、属性要求对象引用”错误;

(3)语法为static <class>(){static constructor body}

//静态构建件BaseClass中,包含对a的赋值,而a的声明是实化成员,引发错误
using System;
class BaseClass
{
    public static int i;
    public int a = 0;
    static BaseClass()
    {
        i = 10;
        a = 15;
    }
    public void Print()
    {
        Console.WriteLine("The value of i is " + i);
        Console.WriteLine("The value of a is " + a);
    }
}
class StaticCons1
{
    public static void Main(string[] args)
    {
        BaseClass oBaseClass = new BaseClass();
        oBaseClass.Print();
    }
}

  

二、应用

1.缺省构建件

   除system.object以外的所有对象--system.object调用system.object.object()进行初始化,派生类的构建件在将要(immediatedly before)执行该构建件的第一行语句之前,默认要首先访问基类的无参构建件。见下例:

 

//如果派生类内不显式指定,默认地调用基类无参构建子
using System;

class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine("[BaseClass.BaseClass] " + "Constructor called");
    }
}

class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        Console.WriteLine("[DerivedClass.Derived] " + "Constructor called");
    }
}

class DefaultInitializer
{
    public static void Main()
    {
        Console.WriteLine("[Main] Instantiating a " + "DerivedClass object");
        DerivedClass derived = new DerivedClass();

    }
}

输出的结果(证明了这一点):


 

从MSIL也可以清楚地看到:



 

2.创建-初始化件(constructor initializer)  

(1)注意这是由两个系统级'元素'合成,用于显式指明使用哪个类、哪个构建件;

(2)派生类显式创建初始化件有两种形式,可以使用关键字:base和this来实现。

        base用于显式指出该构建件使用基类中的某(一般用于多参的构建子)构建件;

        this用于显式指出该构建件使用“自身类”中的其它某构建件。

        语法形式

        <derivedclass>(derived constructor arguments):base(base constructor arguments){body}

        <derivedclass>(derived constructor arguments1):this(derived constructor arguments2){body}

 

//示例:使用base显式指出互操作调用的构建件,否则指向基类默认构建件!
using System;

class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine("[BaseClass.BaseClass()] " + "Parameterless constructor called");
    }

    public BaseClass(int foo)
    {
        Console.WriteLine("[BaseClass.BaseClass(int foo)] " + "foo = {0}", foo);
    }
}

class DerivedClass : BaseClass
{
    public DerivedClass(int foo) : base(foo)
    {
        Console.WriteLine("[DerivedClass.DerivedClass] " +  "foo = {0}", foo);
    }
}

class BaseInitializer3
{
    public static void Main()
    {
        Console.WriteLine("[Main] Instantiating a " + "DerivedClass object...");
        DerivedClass derived = new DerivedClass(42);

    }
}

 

 (4)在初始化器列表中调用基类的构建件,使用静态成员的示例(only? static members can be used when calling base class constructors in the initializer list)。

//注意base的初始化件列表的声明
using System;

class CommaDelimitedFile
{
    public CommaDelimitedFile(string fileName)
    {
        Console.WriteLine("[CommaDelimitedFile." +
            "CommaDelimitedFile] file name = {0}", fileName);
    }
}

enum TableId
{
    Customers,
    Suppliers,
    Vendors
};

class DbTable : CommaDelimitedFile
{
    static string GetFileName(TableId tableId)
    {
        string fileName;

        switch(tableId)
        {
            case TableId.Customers:
                fileName = "customers.txt";
                break;

            case TableId.Suppliers:
                fileName = "suppliers.txt";
                break;

            case TableId.Vendors:
                fileName = "venders.txt";
                break;

            default:
                throw new ArgumentException("[DbTable." +
                    "GetFileName] Could not resolve table name");
        }

        return fileName;
    }

    public DbTable(TableId tableId) : base(GetFileName(tableId))
    {
        Console.WriteLine("[DbTable.DbTable] tableId = {0}", " +
            tableId.ToString());
    }
}

class BaseInitializer4
{
    public static void Main()
    {
        Console.WriteLine("[Main] Instantiating a " +
            "Customer Table object...");
        DbTable derived = new DbTable(TableId.Customers);

    }
}

 

3.私有构建件(private constructor)

(1)该构建件往往用于内实化或内实现,比如用嵌套类来实现,而从外部却无法初始化类的对象,故常用于singleton(模式)对象。

(2)当从外部实例化包含私有构建件的类型时,会引发基于保护级别(protection level)的报错。

 

4.构建件的异常处理

   构建件允许对异常进行处理,见下例。

 

using System;
class ConsExcep
{
    public ConsExcep(int numer, int dinom)
    {
        try
        {
            int Result = numer / dinom;
            Console.WriteLine("Result is:" + Result);
        }
        catch (Exception oEx)
        {
            Console.WriteLine("Error :" + oEx.Message);
        }
    }
}
class ExcepConstructor
{
    public static void Main(string[] arsg)
    {
        ConsExcep oConsExcep = new ConsExcep(5, 0);
    }
}

 

5.结构中的构建件

(1)必须带参数,故不允许缺省的无参构建器;

(2)允许重载;

 见例. 

using System;
struct structstudent
{
    private string _Sname;
    private string _Class;
    private string _Age;
    public structstudent(string sname, string sclass, string sage)
    {
        _Sname = sname;
        _Class = sclass;
        _Age = sage;
    }
    public void PrintReport()
    {
        Console.WriteLine("Student Report");
        Console.WriteLine("--------------");
        Console.WriteLine("Student Name: " + _Sname);
        Console.WriteLine("Student Class: " + _Class);
        Console.WriteLine("Student Age: " + _Age);
    }
}
class StructCons
{
    public static void Main(string[] args)
    {
        structstudent oSD = new structstudent("Rama", "1st Std", "6");
        oSD.PrintReport();
    }
}

 

小结:

instance的元义,是指特殊的例子或发生什么的一种状况(a particular example,or occurence of something),表明发生的以及当前存在的事实(the fact that it happens or is present)。

 

int i;这句话的含义是什么?--实化。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值