新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C#遍历类的属性 PropertyInfo.Attributes,c#遍历列表

发布时间:2023-09-13 08:07:21

C#遍历类的属性 PropertyInfo.Attributes

在C#中,可使用反射来遍历类的属性,并获得属性的属性(Attribute)信息。首先,需要获得属性的Type对象,然后使用Type对象的GetProperties()方法来获得类的所有属性。接下来,可使用属性的GetCustomAttributes()方法来获得属性的所有属性(Attribute)。
以下是一个示例代码来遍历类的属性并获得属性的属性(Attribute)信息:
```csharp
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`。