溫馨提示×

C#遍歷類的屬性 PropertyInfo.Attributes

c#
小云
149
2023-09-12 04:40:20
欄目: 編程語言

在C#中,可以使用反射來遍歷類的屬性,并獲取屬性的屬性(Attribute)信息。首先,需要獲取屬性的Type對象,然后使用Type對象的GetProperties()方法來獲取類的所有屬性。接下來,可以使用屬性的GetCustomAttributes()方法來獲取屬性的所有屬性(Attribute)。

以下是一個示例代碼來遍歷類的屬性并獲取屬性的屬性(Attribute)信息:

using System;
using System.Reflection;
class MyClass
{
[Obsolete("This property is obsolete.")]
public string MyProperty { get; set; }
}
class Program
{
static void Main()
{
Type myClassType = typeof(MyClass);
PropertyInfo[] properties = myClassType.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Property Name: " + property.Name);
object[] attributes = property.GetCustomAttributes(true);
foreach (var attribute in attributes)
{
Console.WriteLine("Attribute Type: " + attribute.GetType().Name);
Console.WriteLine("Attribute Value: " + attribute.ToString());
}
Console.WriteLine();
}
Console.ReadLine();
}
}

運行上述代碼,將輸出類的屬性名稱以及每個屬性的屬性(Attribute)信息。在示例代碼中,我們定義了一個名為MyClass的類,其中包含一個被標記為Obsolete屬性的屬性MyProperty。運行代碼后,將輸出以下結果:

Property Name: MyProperty
Attribute Type: ObsoleteAttribute
Attribute Value: System.ObsoleteAttribute

從輸出結果可以看出,我們成功獲取了屬性MyProperty的屬性(Attribute)信息,該屬性被標記為Obsolete。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女