C#学习笔记(4)

在像C一样的一些面向过程的语言中并没有class关键字,而是一般使用struct,C#中也有struct关键字,其作用和class相似,但是最大的一点不同就是struct没有办法进行继承,其他的大部分的功能与类相同。

举个例子,把上次实现的Time类改写成struct

    public  struct  Time
    {
        public int month;
        public int year;
        public int day;
    }

 对于类中能实现的构造函数和拷贝构造函数,struct均能实现。

下面来补充说明一下上次没有提及的参数传递。

在类或者struct中定义一个这样的函数

        public void GetTime(int h, int m, int s)
        {
            h = 12;
            m = 34;
            s = 56;
        }

在Main类里面运行以下语句

            Time t2= new Time();
            t2.GetTime(t2.year, t2.month, t2.day);
            Console.WriteLine("{0},      {1},      {2}",t2.year,t2.month,t2.day);

在程序运行结束之后,我们会发现t2实例中的各个变量的值并没有改变,这主要是因为t2这个实例被传递到函数是是作为一个形参,并不会改变实参的值。

如果我们想要通过返回值以外的方式改变实参的值,可以通过ref和out这两个关键字实现

        public void GetTime(ref int h, int m, int s)
        {
            h = 12;
            m = 34;
            s = 56;
        }

如果我们想这样把函数的第一个形参前加上关键字ref,运行结果就会变成这个样子

ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数的任何更改都将反映在该变量中。out 关键字会导致参数通过引用来传递。这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。再实际使用中,我们基本上可以把两个关键字等效。

同时,我们还需要注意另外一点,我们不仅要在函数声明是使用ref或者out关键字,在使用该函数的时候也需要在对应的参数的位置使用ref或者out关键字。

同样,在类和struct中关键字ref和out均可使用。

在C#中,除了类以外还有另外一种实现继承和多态的机制——Interface (接口)。

接口和抽象类非常相似,但是一个类只可以继承一个抽象类,但是却可以继承多个接口。在声明接口的时候我们不能在方法前增加权限作为修饰,也不能写出具体的实现方法。

我们创建一个简单的接口来举例

    public interface Inubmer
    {
        void One(int one);
        void Two(int two);
        void Three(int three);
    }

 创建一个类来继承这个接口

    public class Count : Inubmer
    {
        public void One(int one)
        {
            if(one == 1)
                Console.WriteLine("The number is one.");
            else
                Console.WriteLine("The number is't one.");
        }
        public void Two(int two)
        {
            if(two == 2)
                Console.WriteLine("The number is two.");
            else
                Console.WriteLine("The number is't two.");
        }
        public void Three(int three)
        {
            if (three == 3)
                Console.WriteLine("The number is three.");
            else
                Console.WriteLine("The number is't three.");
        }
    }

 如果一个类继承了一个或者几个接口的话,我们在这类里面必须实现所有接口中的所有方法,否则编译器就会报错,这点与抽象类也不相同,抽象类我们只需要实现我们需要的方法即可。

我们做一个简单的测试

    class Program
    {
        static void Main(string[] args)
        {
            Count test = new Count();
            test.One(1);
            test.One(2);
            test.Two(2);
        }
    }

运行结果如下

类似类的继承,接口之间也可以进行一对一,多对一的扩展

    public interface Iplus : Inubmer
    {
        void Plus(int number);
    }

拓展之后的接口带有原先接口的所有功能,同时也可以增加一些新的功能

我们对原先的Number类进行简单的修改

public class Count : Iplus
{public void Plus(int number)
        {
            number++;
            Console.WriteLine("After plus, the number is "+number.ToString()+".");
        }
}

在Main中测试

test.Plus(3);

测试结果如下:

最后,说明一种特殊情况的处理方法,当一个类继承的多个接口中有同名的方法时,我们最好要显示的注明每一个方法的所属接口,这样能够有效的避免错误的发生。

posted on 2015-04-01 19:09  ljc825  阅读(119)  评论(0编辑  收藏  举报

导航