温馨提示×

C#遍历类的属性 PropertyInfo.Attributes

c#
小云
99
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