首页 > 代码库 > C# in Depth Third Edition 学习笔记-- C#2的一些特性
C# in Depth Third Edition 学习笔记-- C#2的一些特性
1. Partial class: 可以在多个源文件中写一个类。特别适合部分代码自动生成,部分代码手动添加的特性。
编译器在编译前会把所有的源文件合并到意洽。但是一个方法不能在一个文件中开始,在另一个文件中结束。
C#3中独有的pratial 方法:
// Generated.csusing System;partial class PartialMethodDemo{public PartialMethodDemo(){OnConstructorStart();Console.WriteLine("Generated constructor");OnConstructorEnd();}partial void OnConstructorStart();partial void OnConstructorEnd();}using System;partial class PartialMethodDemo{partial void OnConstructorEnd(){Console.WriteLine("Manual code");}}
2. 静态类型static classes
3. 独立的取值方法/赋值属性访问器separate getter/setter property access
string name;public string Name{get { return name; }private set{// Validation, logging etc herename = value;}}
4. 命名空间别名Namespace aliases
using System;using WinForms = System.Windows.Forms;using WebForms = System.Web.UI.WebControls;class Test{static void Main(){Console.WriteLine(typeof(WinForms.Button));Console.WriteLine(typeof(WebForms.Button));}}
C#2 告知编译器使用别名
using System;using WinForms = System.Windows.Forms;using WebForms = System.Web.UI.WebControls;class WinForms {}class Test{static void Main(){Console.WriteLine(typeof(WinForms::Button));Console.WriteLine(typeof(WebForms::Button));}}
全局命名空间别名
using System;class Configuration {}namespace Chapter7{class Configuration {}class Test{static void Main(){Console.WriteLine(typeof(Configuration));Console.WriteLine(typeof(global::Configuration));Console.WriteLine(typeof(global::Chapter7.Test));}}}
外部别名
// Compile with// csc Test.cs /r:FirstAlias=First.dll /r:SecondAlias=Second.dllextern alias FirstAlias;extern alias SecondAlias;using System;using FD = FirstAlias::Demo;class Test{static void Main(){Console.WriteLine(typeof(FD.Example));Console.WriteLine(typeof(SecondAlias::Demo.Example));}}
5. pragma directives
禁用和恢复警告CS0169
public class FieldUsedOnlyByReflection{int x;}If you try to compile listing 7.9, you’ll get a warning message like this:FieldUsedOnlyByReflection.cs(3,9): warning CS0169:The private field ‘FieldUsedOnlyByReflection.x‘ is never used
public class FieldUsedOnlyByReflection{#pragma warning disable 0169int x;#pragma warning restore 0169}
Checksum pragmas
#pragma checksum "filename" "{guid}" "checksum bytes"
6. 非安全代码中的固定大小的缓冲区Fixed-size buffers in unsafe code
7. 把内部成员暴露给选定的程序集
简单情况下的友元程序集
// Compiled to Source.dllusing System.Runtime.CompilerServices;[assembly:InternalsVisibleTo("FriendAssembly")]public class Source{internal static void InternalMethod() {}public static void PublicMethod() {}}// Compiled to FriendAssembly.dllpublic class Friend{static void Main(){Source.InternalMethod();Source.PublicMethod();}}// Compiled to EnemyAssembly.dllpublic class Enemy{static void Main(){// Source.InternalMethod();Source.PublicMethod();}}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。