C# .Net 学习积累 《三》

    技术2022-05-20  38

    一. as 关键字

         as 用于在兼容的引用类型之间执行转换。例如:

    string s = someObject as string; if (s != null) { // someObject is a string. }  

    备注: 

    as 运算符类似于强制转换,所不同的是,当转换失败时,运算符将产生空,而不是引发异常。更严格地说,这种形式的表达式(expression as type)等效于 expression is type ? (type)expression : (type)null

    只是 expression 只被计算一次。 

     

    注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用 cast 表达式来执行。 

     

     

     

    二. 接口 

    接口定义了一个可由类和结构实现的协定。接口可以包含方法、属性、事件、和索引器。接口不提供它所定义的成员的实现——它仅指定该接口的类或结构必须提供的成员。(接口是一种特殊的抽象类) 

    《1》 一个接口声明可以声明零个或多个成员。

    《2》 接口的成员必须是方法、属性、事件或索引器。

    《3》 接口不能包含常量、字段、运算符、实例构造函数、析构函数或类型,也不能包含任何类的静态成员。

    《4》 所以接口成员都隐式的具有public访问属性。

    《5》接口成员声明中包含任何修饰符都属于编译时错误。具体来说,不能使用abstract、public,protected、internal、private、virtual、override、或static来声明接口成员。

    实例:

    namespace interface1 { interface IDrivingLicenseB { void GetLicenseB(); } interface IDrivingLicenseA:IDrivingLicenseB { void GetLicenseA(); } public class Teacher : IDrivingLicenseA { public void GetLicenseB() { Console.WriteLine("Have Got Driving License B."); } public void GetLicenseA() { Console.WriteLine("Have Got Driving License A."); } } public class Student:IDrivingLicenseB { public void GetLicenseA() { Console.WriteLine("Have Got Driving License A."); } public void GetLicenseB() { Console.WriteLine("Have Got Driving License B."); } } class Program { static void DriveCar(string name,object o) { IDrivingLicenseB dl=o as IDrivingLicenseB; if (dl != null) { Console.WriteLine(name+" is starting car..."); } else { Console.WriteLine(name+" aren't allow to drive a car unless have got a Driving License B."); } } static void DriveBus(string name, object o) { IDrivingLicenseA dl = o as IDrivingLicenseA; if (dl != null) { Console.WriteLine(name+" is starting the Bus..."); } else { Console.WriteLine(name+" aren't allow to drive a Bus unless have got a Driving License A."); } } static void Main(string[] args) { Teacher t = new Teacher(); Student s = new Student(); DriveCar("Cheers Li", t); DriveBus("Cheers Li", t); DriveCar("Ling Yang", s); DriveBus("Ling Yang", s); Console.ReadKey(); } } }  

        (一、)显式接口成员实现

                为了实现接口,类或结构可以声明显示接口成员实现(explicit interface member implementation).

                 显式接口成员实现是一种方法、属性、时间或索引器声明,它使用完全限定接口成员名称作为标识符。

                 《1》 在方法调用、属性访问或索引器访问中,不能直接访问“显式接口成员实现”的成员,即使用它的完全限定名也不行。“显式接口成员实现”的成员只能通过接口实例访问,并且在通过接口实例访问时,只能用该接口成员的简单名称来引用。

                 《2》 显式接口成员实现中包含访问修饰符属于编译时错误,而且如果包含abstract,virtual,override或static修饰符也属于编译时错误。

                 《3》 显式接口成员实现具有与其他成员不同的可访问性特征。由于显式接口成员实现永远不能在方法调用或属性访问中通过他们的完全限定名来访问,因此,他们似乎是私有的(private),但是他们可以通过接口实例来访问,所以他们似乎又是共有的(public)。

    实例:

     

     


    最新回复(0)