C#中的一些常用屬性

來源:互聯網
上載者:User
C#中一些預設的預定義屬性,見下表:

預定義的屬性 有效目標 說明
AttributeUsage Class 指定另一個屬性類的有效使用方式
CLSCompliant 全部 指出程式元素是否與CLS相容
Conditional Method 指出如果沒有定義相關聯的字串,編譯器就可以忽略對這個方法的任何調用
DllImport Method 指定包含外部方法的實現的DLL位置
STAThread Method(Main) 指出程式的預設執行緒模式為STA
MTAThread Method(Main) 指出程式的預設模型為多線程(MTA)
Obsolete 除了Assembly、Module、Parameter和Return 將一個元素標示為不可用,通知使用者此元素將被從未來的產品
ParamArray Parameter 允許單個參數被隱式地當作params(數組)參數對待
Serializable Class、Struct、enum、delegate 指定這種類型的所有公用和私人欄位可以被序列化
NonSerialized Field 應用於被標示為可序列化的類的欄位,指出這些欄位將不可被序列化
StructLayout Class、struct 指定類或結構的資料布局的性質,比如Auto、Explicit或sequential
ThreadStatic Field(靜態) 實現線程局部儲存(TLS)。不能跨多個線程共用給定的靜態欄位,每個線程擁有這個靜態欄位的副本

下面介紹幾種常用的屬性1.[STAThread]和[MTAThread]屬性class Class1{        [STAThread]        Static void Main( string[] args )        {        }}使用STAThread屬性將程式的預設執行緒模式指定為單執行緒模式。注意,執行緒模式隻影響使用COM interop的應用程式,將這個屬性應用於不使用COM interop的程式將不會產生任何效果。2. AttributeUsage屬性        除了用於標註常規C#類型的自訂屬性以外,還可以使用AttributeUsage屬性定義你使用這些屬性的方式。檔案記錄的AttributeUsage屬性調用用法如下:[AttributeUsage( validon , AllowMutiple = allowmutiple , Inherited = inherited )]Validon參數是AttributeTargets類型的,這個枚舉值的定義如下:public enum AttributeTargets{        Assembly = 0x0001,        Module = 0x0002,        Class = 0x0004,        Struct = 0x0008,        Enum = 0x0010,        Constructor = 0x0020,        Method = 0x0040,        Property = 0x0080,        Field = 0x0100,        Event = 0x200,        Interface = 0x400,        Parameter = 0x800,        Delegate = 0x1000,        All = Assembly | Module | Class | Struct | Enum | Constructor| Method | Property|                    Filed| Event| Interface | Parameter | Deleagte ,        ClassMembers = | Class | Struct | Enum | Constructor | Method | Property | Field |                    Event | Delegate | Interface }AllowMultiple決定了可以在單個欄位上使用某個屬性多少次,在預設情況下,所有的屬性都是單次使用的。樣本如下:[AttributeUsage( AttributeTargets.All , AllowMultiple = true )]public class SomethingAttribute : Attribute{        public SomethingAttribute( string str )        {        }}//如果AllowMultiple = false , 此處會報錯[Something(“abc”)][Something(“def”)]class Myclass{}Inherited參數是繼承的標誌,它指出屬性是否可以被繼承。預設是false。

Inherited AllowMultiple 結果
true false 派生的屬性覆蓋基屬性
true false 派生的屬性和基屬性共存
程式碼範例:using System;using System.Reflection; namespace AttribInheritance{     [AttributeUsage(          AttributeTargets.All,          AllowMultiple=true,//       AllowMultiple=false,          Inherited=true     )]     public class SomethingAttribute : Attribute     {         private string name;         public string Name         {              get { return name; }              set { name = value; }         }          public SomethingAttribute(string str)         {              this.name = str;         }     }              [Something("abc")]     class MyClass     {     }      [Something("def")]     class Another : MyClass     {     }              class Test     {         [STAThread]         static void Main(string[] args)         {              Type type =                  Type.GetType("AttribInheritance.Another");              foreach (Attribute attr in                  type.GetCustomAttributes(true))//                type.GetCustomAttributes(false))              {                  SomethingAttribute sa =                       attr as SomethingAttribute;                  if (null != sa)                  {                  Console.WriteLine(                           "Custom Attribute: {0}",                           sa.Name);                  }              }          }     }}當AllowMultiple被設定為false時,結果為:Custom Attribute : def當AllowMultiple被設定為true時,結果為:Custom Attribute : defCustom Attribute : abc注意,如果將false傳遞給GetCustomAttributes,它不會搜尋繼承樹,所以你只能得到派生的類屬性。 3.Conditional 屬性        你可以將這個屬性附著於方法,這樣當編譯器遇到對這個方法調用時,如果沒有定義對應的字串值,編譯器就忽略這個調用。例如,以下方法是否被編譯取決於是否定義了字串“DEGUG”:[Condition(“DEBUG”) ]public void SomeDebugFunc(){        Console.WriteLine(“SomeDebugFunc”);}using System;using System.Diagnostics; namespace CondAttrib{     class Thing     {         private string name;         public Thing(string name)         {              this.name = name;              #if DEBUG                  SomeDebugFunc();              #else                  SomeFunc();              #endif         }         public void SomeFunc()              { Console.WriteLine("SomeFunc"); }          [Conditional("DEBUG")]         [Conditional("ANDREW")]         public void SomeDebugFunc()              { Console.WriteLine("SomeDebugFunc"); }     }      public class Class1     {         [STAThread]         static void Main(string[] args)         {              Thing t = new Thing("T1");         }     }} 4. Obsolete 屬性        隨著代碼不斷的發展,你很可以會有一些方法不用。可以將它們都刪除,但是有時給它們加上適當的標註比刪除它們更合適,例如:using System; namespace ObsAttrib{     class SomeClass     {         [Obsolete("Don't use OldFunc, use NewFunc instead", true)]         public void OldFunc( ) { Console.WriteLine("Oops"); }          public void NewFunc( ) { Console.WriteLine("Cool"); }     }      class Class1     {         [STAThread]         static void Main(string[] args)         {              SomeClass sc = new SomeClass();              sc.NewFunc();//            sc.OldFunc();     // compiler error         }     }}我們將Obsolete屬性的第二個參數設定為true,當調用時函數時編譯器會產生一個錯誤。E:\InsideC#\Code\Chap06\ObsAttrib\ObsAttrib\Class1.cs(20): 'ObsAttrib.SomeClass.OldFunc()' 已淘汰: 'Don't use OldFunc, use NewFunc instead' 5. DllImport和StructLayout屬性        DllImport可以讓C#代碼調用機器碼中的函數,C#代碼通過平台叫用(platform invoke)這個運行時功能調用它們。        如果你希望運行時環境將結構從Managed 程式碼正確地編組現Unmanaged 程式碼(或相反),那麼需要為結構的聲明附加屬性。為了使結構參數可以被正確的編組,必須使用StructLayout屬性聲明它們,指出資料應該嚴格地按照聲明中列出的樣子進行布局。如果不這麼做,資料將不能正確地被編組,而應用程式可能會出錯。using System;using System.Runtime.InteropServices;    // for DllImport namespace nativeDLL{     public class Test     {//       [DllImport ("user32.dll")]           // all the defaults are OK         [DllImport("user32", EntryPoint="MessageBoxA",              SetLastError=true,              CharSet=CharSet.Ansi, ExactSpelling=true,              CallingConvention=CallingConvention.StdCall)]         public static extern int MessageBoxA (              int h, string m, string c, int type);          [StructLayout(LayoutKind.Sequential)]         public class SystemTime {              public ushort wYear;              public ushort wMonth;              public ushort wDayOfWeek;              public ushort wDay;              public ushort wHour;              public ushort wMinute;              public ushort wSecond;              public ushort wMilliseconds;         }          [DllImport ("kernel32.dll")]         public static extern void GetLocalTime(SystemTime st);          [STAThread]         public static void Main(string[] args)         {              MessageBoxA(0, "Hello World", "nativeDLL", 0);               SystemTime st = new SystemTime();              GetLocalTime(st);              string s = String.Format("date: {0}-{1}-{2}",                  st.wMonth, st.wDay, st.wYear);              string t = String.Format("time: {0}:{1}:{2}",                  st.wHour, st.wMinute, st.wSecond);              string u = s + ", " + t;               MessageBoxA(0, u, "Now", 0);         }     }} 6. 配件屬性        當使用.NET產生任何類型的C#工程時,會自動的產生一個AssemblyInfo.cs原始碼檔案以及應用程式原始碼檔案。AssemblyInfo.cs中含有配件中代碼的資訊。其中的一些資訊純粹是資訊,而其它資訊使運行時環境可以確保惟一的命名和版本號碼,以供重用你的配件的客戶代碼使用。 7. 內容屬性        .NET櫃架還提供了另一種屬性:內容屬性。內容屬性提供了一種截取機制,可以在類的執行個體化和方法調用之前和之後進行處理。這種功能用於對象遠程調用,它是從基於COM的系統所用的COM+元件服務和Microsoft Transaction Services(MTS)。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.