您好,登錄后才能下訂單哦!
在C#中,特性(Attribute)是一種用于為代碼添加元數(shù)據(jù)的機(jī)制
以下是如何創(chuàng)建自定義特性并將其應(yīng)用于類和方法的示例:
System.Attribute
。using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CustomMetadataAttribute : Attribute
{
public string Key { get; set; }
public string Value { get; set; }
public CustomMetadataAttribute(string key, string value)
{
Key = key;
Value = value;
}
}
using System;
[CustomMetadata("ClassKey", "ClassValue")]
public class MyClass
{
[CustomMetadata("MethodKey", "MethodValue")]
public void MyMethod()
{
// ...
}
}
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Type type = typeof(MyClass);
// 獲取類上的特性
object[] classAttributes = type.GetCustomAttributes(typeof(CustomMetadataAttribute), false);
foreach (CustomMetadataAttribute attribute in classAttributes)
{
Console.WriteLine($"Class - Key: {attribute.Key}, Value: {attribute.Value}");
}
// 獲取方法上的特性
MethodInfo methodInfo = type.GetMethod("MyMethod");
object[] methodAttributes = methodInfo.GetCustomAttributes(typeof(CustomMetadataAttribute), false);
foreach (CustomMetadataAttribute attribute in methodAttributes)
{
Console.WriteLine($"Method - Key: {attribute.Key}, Value: {attribute.Value}");
}
}
}
運(yùn)行上述代碼,你將看到以下輸出:
Class - Key: ClassKey, Value: ClassValue
Method - Key: MethodKey, Value: MethodValue
這樣,你就可以根據(jù)需要對特性進(jìn)行統(tǒng)計和分析。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。