《CLR via C#》笔记:第2部分 设计类型(5)

  • 本博客所总结书籍为《CLR via C#(第4版)》清华大学出版社,2021年11月第11次印刷(如果是旧版书籍或者pdf可能会出现书页对不上的情况)
  • 你可以理解为本博客为该书的精简子集,给正在学习中的人提供一个“glance”,以及对于部分专业术语或知识点给出解释/博客链接。
  • 【本博客有如下定义“Px x”,第一个代表书中的页数,第二个代表大致内容从本页第几段开始。(如果有last+x代表倒数第几段,last代表最后一段)】
  • 电子书可以在博客首页的文档-资源归档中找到,或者点击:传送门自行查找。如有能力请支持正版。(很推荐放在竖屏上阅读本电子书,这多是一件美事)
  •  个人博客网址:《CLR via C#》笔记:第2部分 设计类型(5)-Sugar的博客,如文章转载中出现例如传送门失效等纰漏,建议直接访问原博客网址。

  • 欢迎加群学习交流:637959304 进群密码:(CSGO的拆包密码) 

目录

第十三章 接口

类和接口继承

定义接口

继承接口

关于调用接口方法的更多探讨

隐式和显示接口方法实现(幕后发生的事情)

泛型接口

泛型和接口约束

实现多个具有相同方法名和签名的接口

用显式接口方法实现来增强编译时类型安全性

谨慎使用显示接口方法实现

设计:基类还是接口


第十三章 接口

  • CLR不支持多继承,CLR只通过接口提供了“缩水版”的多继承。

类和接口继承

  • Microsoft .NET Framework提供了System.Object类,它定义了4个公共实例方法:ToString,Equals,GetHashCode和 GetType。该类是其他所有类的根或者说终极基类。换言之,所有类都继承了Object的4个实例方法。这还意味着只要代码能操作Object类的实例,就能操作任何类的实例。(P259 last2)
    从Object派生的任何类都继承了:1、方法签名 2、方法实现

定义接口

  • 接口:CLR还允许开发人员定义接口:接口实际只是对一组方法签名进行了统一命名。这些方法不提供任何实现。类通过指定接口名称来继承接口,而且必须显式实现接口方法,否则CLR会认为此类型定义无效。C#编译器和CLR允许一个类继承多个接口,继承的所有接口方法都必须实现。(P260 2)
  • 接口能够定义事件、无参属性,有参数性(C#的索引器),静态方法,静态字段,常量和静态构造器。但不允许定义符合CLS标准的接口,因为有的编程语言不能定义或访问他们(P260 3)
  • C#用interface定义接口。根据约定,接口类型名称以大写字母I开头,这样方便在源代码中辨认接口类型。CLR支持泛型接口和接口中的泛型方法。(P261 2)

继承接口

  • C#编译器要求将实现接口的方法(后文简称为“接口方法”)标记为 public。CLR要求将接口方法标记为 virtual。不将方法显式标记为 virtual,编译器会将它们标记为 virtual和sealed;这会阻止派生类重写接口方法。将方法显式标记为 virtual,编译器就会将该方法标记为virtual(并保持它的非密封状态),使派生类能重写它。(P262 1)
  • 派生类不能重写sealed 的接口方法。但派生类可重新继承同一个接口,并为接口方法提供自己的实现。在对象上调用接口方法时,调用的是该方法在该对象的类型中的实现。(P262 2)

关于调用接口方法的更多探讨

  • FCL的System.String类型(可以看一下书中代码示例)(P263 last2)

隐式和显示接口方法实现(幕后发生的事情)

  • C#编译器为支持接口所做的工作(P265 1)
  • 在C#中,将定义方法的那个接口的名称作为方法名前缀(例如 IDisposable.Dispose),就会创建显式接口方法实现(Explicit Interface Method Implementation,EIMI)。定义时不能标记为vitual,不能指定可访问性。(P265 last)

泛型接口

  • 泛型接口的好处:1、提供了出色的编译时类型安全性。2、处理类型时装箱次数少 3、类可以实现同一个接口若干次,只要每次使用不同的类型参数。(P266 3)

1

2

3

4

5

6

7

8

9

private void fun()

{

    int x = 1,y = 2;

    IComparable<int> c = x;//泛型接口<int>

    c.CompareTo(y);//y不在这里装箱

    c.CompareTo("2");//错误,提示string不能转int

}

泛型和接口约束

  • 泛型接口约束的好处:1、可将泛型类型参数约束为多个接口。如此,传递的参数类型必须实现全部接口约束。 2、传递值类型的实例时减少装箱(P268 2)

实现多个具有相同方法名和签名的接口

  • 实现定义两个接口的类型,那么必须实现这些接口的方法,因此要告诉C#编译器每个同名方法对应的是哪个接口的实现。(P269 last2)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

public interface IWindow

{

    Object GetMEenu();

}

public interface IRestaurant

{

    Object GetMEenu();

}

public sealed class fun : IWindow,IRestaurant

{

    Object IWindow.GetMEenu(){}

    Object IRestaurant.GetMEenu(){}

    public Object GetMEenu(){}//该方法可选与接口无关

}

用显式接口方法实现来增强编译时类型安全性

  • 有时由于不存在泛型版本,所以仍需实现非泛型接口。接口的任何方法接受System.Object类型的参数或返回System.Object类型的值,就会失去编译时的类型安全性,装箱也会发生。可以用显式接口方法在某种程度上改善这个问题。(P270 1)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public interface IComparable

{

    int CompareTo(Object other);

}

internal struct fun : Icomparable

{

    private int m_x;

    public fun(int x) {m_x = x}

    public int CompareTo(Object other)

    {

        return (m_x-((fun)other).m_x);

    }

}

public static void Main()

{

    fun v = new fun(0);

    Object o = new Object();

    int n = v.CompareTo(v);//不希望的装箱操作

    n = v.CompareTo(o);//InvalidCastException异常

}

  • 上述代码存在问题:1、不希望的装箱操作 2、缺乏类型安全性(P270 last)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

//EIMI修改后版本

internal struct fun : IComparable

{

    private int m_x;

    public fun(int x) {m_x = x}

    public int CompareTo(Object other)

    {

        return (m_x-((fun)other).m_x);

    }

//定义接口类型的变量会再次失去编译时的类型安全性,且会再次发生装箱

    int IComparable.CompareTo(Object other)

    {

        return CompareTo((fun)other);

    }

}

谨慎使用显示接口方法实现

  • EIMI问题:1、没有文档解释类型具体如何实现一个EIMI方法名也没有visual studio只能感知支持。2、值类型的实例在转换成接口时装箱3、EIMI不能由派生类调用(P271 last)

设计:基类还是接口

  • 基类还是接口的选择思路:1、IS-A对比CAN-DO关系(IS-A代表属于,a属于b。CAN-DO代表能做某事,类型能将自己的实例转化为另一个类型)2、易用性 3、一致性实现 4、版本控制(P274 1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CLR via C# 第4 英文PDFKristin, words cannot express how /feel about our life together. cherish our family and all our adventures. I'm filled each day with love for Aidan (age 9)and Grant (age 5), you both have been an inspira- tion to me and have taught me to play and have fun Watching the two of you grow up has been so rewarding and enjoyable for me. am lucky to be able to partake in your lives. love and ap preciate you more than you could ever know Contents at a glance Introduction PART I CLR BASICS CHAPTER 1 The clr's execution model CHAPTER 2 Building, Packaging, Deploying, and Administering Applications and Types 33 chaPTeR 3 Shared Assemblies and Strongly Named Assemblies 65 PART I DESIGNING TYPES CHAPTER 4 Type Fundamentals 91 CHAPTER 5 Primitive, Reference, and Value Types 111 CHAPTER 6 Type and Member Basics 151 CHAPTER 7 Constants and fields 175 chaPTer 8 Methods 181 chaPTer 9 Parameters 209 CHAPTER 10 Properties 227 CHAPTER 11 Events 249 CHAPTER 12 Generics 265 CHAPTER 13 Interfaces 295 PARTⅢ ESSENTIAL TYPES CHAPTER 14 Chars, Strings, and Working with Text 317 CHAPTER 15 Enumerated Types and Bit Flags 361 CHAPTER 16 Arrays 373 CHAPTER 17 Delegates 391 CHAPTER 18 Custom Attributes 421 CHAPTER 19 Nullable value Types 441 PART IV CORE FACILITIES CHAPTER 20 Exceptions and state management 451 CHAPTER 21 The Managed Heap and Garbage Collection 505 CHAPTER 22 CLR Hosting and AppDomains 553 CHAPTER 23 Assembly Loading and reflection 583 CHAPTER 24 Runtime serialization 611 CHAPTER 25 Interoperating with WinRT Components 643 PAR V THREADING ChaPTEr 26 Thread basics 669 CHAPTER 27 Compute-Bound Asynchronous Operations 691 CHAPTER 28 IyO-Bound Asynchronous Operations 727 CHAPTER 29 Primitive thread Synchronization Constructs 757 CHAPTER 30 Hybrid Thread Synchronization Constructs 789 Index 823 Contents at a glance Contents Introduction XX PART CLR BASICS Chapter 1 The Clrs Execution Model 3 Compiling Source Code into Managed Modules Combining managed modules into assemblies Loading the Common Language Runtime 8 Executing Your Assembly's Code 11 IL and∨ erification 16 Unsafe Code The Native Code generator tool: ngen. exe 19 The Framework Class Library 22 The Common Type System The Common Language Specification Interoperability with Unmanaged Code 30 Chapter 2 Building, Packaging, Deploying, and Administering Applications and Types 33 NET Framework Deployment Goals 34 Building Types into a Module 35 Response Fil 36 A Brief Look at metadata 38 What do you think of this book We want to hear from you Microsoft is interested in hearing your feedback so we can continually improve our books and learning resources for you. To participate in a brief online survey, please visit microsoft. com/learning/booksurvey Combining Modules to Form an Assembly 45 Adding Assemblies to a Project by Using the Visual Studio IDE.51 Using the assembly Linker Adding Resource Files to an Assembly 53 Assembly Version Resource Information .54 Version numbers ..58 Culture Simple Application Deployment(Privately deployed Assemblies)...60 Simple Administrative Control(Configuration) 62 Chapter 3 Shared Assemblies and Strongly Named Assemblies 65 Two Kinds of Assemblies, Two Kinds of Deployment 66 Giving an Assembly a Strong Name 67 The global Assembly Cache 72 Building an Assembly That References a Strongly Named Assembly..74 Strongly named assemblies are tamper-Resistant 75 Delayed Signing Privately Deploying Strongly Named Assemblies How the Runtime Resolves Type References 80 Advanced Administrative Control( Configuration) 83 Publisher Policy control 86 PART I DESIGNING TYPES Chapter 4 Type Fundamentals 91 All Types Are Derived from System Object .91 Casting Between Types 93 Casting with the C# is and as Operators Namespaces and assemblies 97 How Things relate at Run time .101 Chapter 5 Primitive, Reference, and Value Types 111 Programming Language Primitive Types 111 Checked and Unchecked Primitive Type Operations 115 Reference Types and value Types 118 Boxing and Unboxing Value Types 124 Changing Fields in a Boxed Value Type by Using Interfaces and Why You Shouldnt Do This) 136 Object Equality and Identity 139 Object hash Codes .142 The dynamic Primitive Type ......144 Chapter 6 Type and member Basics 151 The Different Kinds of Type Members .151 Type visibilit 154 Friend assemblies 154 Member accessibility .156 Static Classes ...158 Partial Classes, Structures, and Interfaces .159 Components, Polymorphism, and Versioning 160 How the CLR Calls Virtual Methods, Properties, and Events 162 Using Type Visibility and Member Accessibility Intelligently...166 Dealing with Virtual Methods When Versioning Types 16 Chapter 7 Constants and Fields 175 Constants 175 Fⅰe|ds ...177 Chapter 8 Methods 181 Instance Constructors and Classes(Reference Types) 181 Instance Constructors and Structures(Value Types) 184 Type Constructors 187 Contents x Operator Overload Methods 191 Operators and Programming Language Interoperability 193 Conversion Operator Methods 195 Extension method 198 Rules and guidelines ....,200 Extending Various Types with Extension Methods 201 The Extension Attribute 203 Partial Methods 204 Rules and guidelines 207 Chapter 9 Parameters 209 Optional and Named Parameters 209 Rules and guidelines 210 The defaultParameter value and optional Attributes 212 Implicitly Typed Local Variabl 212 Passing parameters by reference to a Method 214 Passing a variable Number of arguments to a Method 220 Parameter and Return Type Guidelines 223 Const-nes 224 Chapter 10 Properties 227 Parameterless Properties 227 Automatically Implemented Properties 231 Defining Properties Intelligently 232 Object and collection Initializers 235 Anonymous Type .237 The System. Tuple type 240 Parameterful Properties 242 The performance of calling property accessor Methods 247 Property Accessor Accessibility 248 Generic prop A roperty Access 248
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值