C#学习笔记 Attribute(特性)

简单地说,特性(Attribute)是与类、结构、方法等元素相关的额外信息,是对元信息的扩展。通过Attribute可以使程序、甚至语言本身的功能得到增强。
Attribute是C#中一种特有的语法成分,它可以作用于各种语言要素,如命名空间、类、方法、字段、属性、索引器,等等,都可以附加上一些特定的声明信息。Attribute与元数据一起存储于程序集中,编译器或者其他程序可以读取并利用这些信息。

系统中已经定义了一些Attribute来表示不同的Attribute,用户也可以自己定义Attribute。所有Attribute类都是System.Attribute的直接或间接子类,并且名字都以Attribute结尾。在程序中使用Attribute的一般方式是这样的:
在相关的程序元素(如类、类中的方法)的前面,加上方括号([]),并且在方括号中规定Attribute的种类,以及该Attribute所带的参数。
System.ObsoleteAttribute为例它用在各种程序元素的前面,用以标记这个元素已经过时或作废,不应在新版本中使用。

	[Obsolete("Div已废弃, 请改用Div2")]
	public static int Div(int a, int b) {
    
     ... }

表示Div方法已过时,如果调用该方法,编译时会发出一个警告信息。具体的信息在Obsolete的参数中用一个字符串来指明。
更多示例:

using System;
using System.Reflection;

namespace ConsoleApp10Attribute
{
    
    
	[AttributeUsage(AttributeTargets.Class |
		AttributeTargets.Method,
		AllowMultiple = true)]
	public class HelpAttribute : System.Attribute
	{
    
    
		public readonly string Url;
		public string Topic {
    
     get => topic; set => topic = value; }
		private string topic;

		public HelpAttribute(string url) {
    
    
			this.Url = url;
		}
	}

	[HelpAttribute("https://msvc/MyClassInfo", Topic = "Test"),
		Help("https://my.com/about/class")]
	class MyClass
	{
    
    
		[Help("http://my.com/about/method")]
		public void MyMethod(int i) {
    
    
			return;
		}
	}

	class MemberInfo_GetCustomAttributes
	{
    
    
		static void Main(string[] args) {
    
    
			Console.WriteLine("Hello World!");

			Type myType = typeof(MyClass);

			object[] attributes = myType.GetCustomAttributes(false);
			for (int i = 0; i < attributes.Length; i++) {
    
    
				PrintAttributeInfo(attributes[i]);
			}

			MemberInfo[] myMembers = myType.GetMembers();
			for (int i = 0; i < myMembers.Length; i++) {
    
    
				Console.WriteLine("\nNumber {0}: ", myMembers[i]);
				Object[] myAttributes = myMembers[i].GetCustomAttributes(false);
				for (int j = 0; j < myAttributes.Length; j++) {
    
    
					PrintAttributeInfo(myAttributes[j]);
				}
			}
		}

		static void PrintAttributeInfo(object attr) {
    
    
			if (attr is HelpAttribute) {
    
    
				HelpAttribute attrh = (HelpAttribute)attr;
				Console.WriteLine("----Url: " + attrh.Url + "  Topic: " + attrh.Topic);
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_45349225/article/details/114156347