C#スタディノート属性(特性)

簡単に言えば、属性は、クラス、構造、メソッドなどの要素に関連する追加情報であり、メタ情報の拡張です。属性を介して、プログラムの機能、さらには言語自体を強化することができます。
属性は、C#の一意の文法コンポーネントです。名前空間、クラス、メソッド、フィールド、属性、インデクサーなどのさまざまな言語要素に作用し、特定の宣言情報を添付できます。属性とメタデータは一緒にアセンブリに格納され、コンパイラまたは他のプログラムはこの情報を読み取って使用できます。

一部の属性は、さまざまな属性を表すためにシステムで定義されており、ユーザーは自分で属性を定義することもできます。すべての属性クラスはSystem.Attributeの直接または間接のサブクラスであり、それらの名前はAttributeで終わります。プログラムで属性を使用する一般的な方法は次のとおりです。
関連するプログラム要素(クラスやクラスのメソッドなど[])の前に上括弧()を追加し、角括弧で属性のタイプを指定し、属性にはパラメーターを指定します。
としてSystem.ObsoleteAttribute、さまざまなプログラム要素の前で使用され、この要素が廃止または廃止されていることを示し、新しいバージョンでは使用しないでください。

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

Divメソッドが古くなっていることを示します。このメソッドが呼び出されると、コンパイル中に警告メッセージが発行されます。特定の情報は、廃止されたパラメータの文字列で示されます。
その他の例:

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