標籤:winform blog http 使用 檔案 io for 2014
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. 把內部成員暴露給選定的程式集
簡單情況下的friend 組件
// 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();}}