日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 特性(Attribute)

發布時間:2023/12/13 C# 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# 特性(Attribute) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

個人定義:不侵入對象的情況下,添加對象附注信息。

官方定義:將預定義的系統信息或用戶定義的自定義信息與目標元素相關聯。目標元素可以是程序集、類、構造函數、委托、枚舉、事件、字段、接口、方法、可移植可執行文件模 ? 塊、參數、屬性 (Property)、返回值、結構或其他屬性 (Attribute)。提供的信息也稱為元數據,元數據可由應用程序在運行時進行檢查以控制程序處理數據的方式,也可以由外部工具在運行前檢查以控制應用程序處理或維護自身的方式。

.Net 框架提供了三種預定義特性:

  • AttributeUsage
  • Conditional
  • Obsolete

示例: 讀取枚舉值上加的 特性信息

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace MyAttribute {[Obsolete("這是一個過期特性")]public enum EnumState{ [Remark("我是打開")]//[Remark("")]Open =1,[Remark("我是關閉")]Close=2} }

?

using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks;namespace MyAttribute {//1.特性的適用范圍 2.特性是否允許用多次 3.特性是否被派生類繼承[AttributeUsage(AttributeTargets.All,AllowMultiple =true, Inherited =true)]//被調用時執行條件編譯,取決于指定的值(如“DEBUG”,"RELEASE"...)[Conditional("DEBUG")]public class RemarkAttribute:Attribute{public string remark;public string Remark{get { return remark; }}public RemarkAttribute(string remark){this.remark = remark;}}public static class RemarkExtend{public static string RemarkDescription(this EnumState state){Type type = typeof(EnumState);FieldInfo info= type.GetField(state.ToString());object[] remarkCustomAttribute= info.GetCustomAttributes(typeof(RemarkAttribute),false); if(remarkCustomAttribute != null && remarkCustomAttribute.Length>0){RemarkAttribute remarkattribute = remarkCustomAttribute[0] as RemarkAttribute;return remarkattribute.Remark;}else{return state.ToString();}}} }

?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace MyAttribute {class Program{static void Main(string[] args){EnumState state = EnumState.Open;Console.WriteLine(state.RemarkDescription());Console.Read();}} }

至此,關于特性的學習就到此結束了,謝謝您的閱讀。

特性還有很多高級的用法,博主只是小試牛刀,希望本文能夠幫到你,當然若有不完善地方,歡迎斧正。

參考MSDN:https://msdn.microsoft.com/zh-cn/library/system.attribute(VS.80).aspx

?

轉載于:https://www.cnblogs.com/jdzhang/p/6910900.html

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的C# 特性(Attribute)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。