【发布时间】:2026-02-15 11:00:01
【问题描述】:
我正在尝试通过反射设置一个值。我创建了这个小测试程序
struct headerIndexes
{
public int AccountNum{ get; set; }
public int other { get; set; }
public int items { get; set; }
}
static void Main(string[] args)
{
headerIndexes headers = new headerIndexes();
headers.AccountNum = 1;
Console.WriteLine("Old val: {0}", headers.AccountNum);
foreach (var s in headers.GetType().GetProperties())
{
if (s.Name == "AccountNum")
s.SetValue(headers, 99, null);
}
Console.WriteLine("New val: {0}", headers.AccountNum);
Console.ReadKey();
}
通过程序,我看到它正确地执行了命令s.SetValue(headers, 99, null);,但是当 setValue 运行时 headers.AccountNum 的值保持为 1。
我错过了一个明显的步骤吗?
【问题讨论】:
标签: c# reflection struct