- 步骤:
- 使用
Type
类获取目标类的类型对象。可以通过typeof
关键字或者GetType
方法获取。
- 使用
Type
类的GetProperties
方法获取类的所有公共属性。该方法会返回一个PropertyInfo
数组,每个PropertyInfo
对象代表一个属性。
- 遍历
PropertyInfo
数组,通过PropertyInfo
的Name
属性获取属性名称,通过PropertyInfo
的PropertyType
属性获取属性类型。
- 代码示例:
using System;
using System.Reflection;
class Program
{
class MyClass
{
public int MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
}
static void Main()
{
// 获取MyClass的类型对象
Type type = typeof(MyClass);
// 获取所有公共属性
PropertyInfo[] properties = type.GetProperties();
// 遍历属性并输出名称和类型
foreach (PropertyInfo property in properties)
{
Console.WriteLine($"属性名称: {property.Name}, 属性类型: {property.PropertyType}");
}
}
}