通过反射设置auto-property's值

本文关键字:auto-property 反射 设置 | 更新日期: 2023-09-27 18:03:20

我看过各种关于如何通过反射调用属性的私有setter的线程。但是,没有setter的auto-properties怎么办?

public class Test
{
    public string Property { get; } = "";
}

是否可以使用反射来设置这个只读属性的值?

  • PropertyInfo.SetMethod返回null
  • PropertyInfo.SetValue失效

任何想法?

通过反射设置auto-property's值

是否可以使用反射来设置这个只读属性的值?

。这些属性由只读字段支持。There 没有setter;在构造函数中执行的任何赋值都直接写入字段。

如果你的设计让你想通过反射写入只读属性,你应该重新审视你的设计:)