我看过各种关于如何通过反射调用属性的私有(private) setter 的线程。但是,如果没有 setter 的自动属性呢?
public class Test
{
public string Property { get; } = "";
}
是否可以使用反射设置此只读属性的值?
PropertyInfo.SetMethod
返回 nullPropertyInfo.SetValue
失败
有什么想法吗?
最佳答案
Is it possible to set the value of this readonly property using reflection?
没有。这些属性由只读字段支持。 没有二传手;在构造函数中执行的任何赋值都直接写入字段。
如果你的设计让你想通过反射写入只读属性,你应该重新审视你的设计:)
关于c# - 通过反射设置自动属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31480933/