using System;
using System.Reflection;
public class MyClass
{
public int Property1 { get; set; } = 42;
public string Property2 { get; set; } = "Hello, World!";
public double Property3 { get; set; } = 3.14;
// 其他属性和方法
}
public class Program
{
public static void Main()
{
// 创建 MyClass 的实例
MyClass myObject = new MyClass();
// 获取类型信息
Type type = typeof(MyClass);
// 获取所有公共属性
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
// 输出所有公共属性的名称和值
Console.WriteLine($"类 {type.Name} 中的公共属性及其值:");
foreach (PropertyInfo property in properties)
{
// 使用 GetValue 方法获取属性值
object value = property.GetValue(myObject);
// 输出属性名称和值
Console.WriteLine($"{property.Name}: {value}");
}
// 也可以修改属性值并再次输出以验证更改
myObject.Property1 = 100;
Console.WriteLine($"修改后的 Property1: {myObject.Property1}");
}
}