简体   繁体   English

通过反射设置auto-property的值

[英]Set auto-property's value via reflection

I've seen various threads on how to call a property's private setter via reflection. 我已经看到了关于如何通过反射调用属性的私有setter的各种线程。 However, what about auto-properties without a setter? 但是,没有setter的自动属性呢?

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

Is it possible to set the value of this readonly property using reflection? 是否可以使用反射设置此只读属性的值?

  • PropertyInfo.SetMethod returns null PropertyInfo.SetMethod返回null
  • PropertyInfo.SetValue fails PropertyInfo.SetValue失败

Any ideas? 有任何想法吗?

Is it possible to set the value of this readonly property using reflection? 是否可以使用反射设置此只读属性的值?

No. Those properties are backed by read-only fields. 不会。这些属性由只读字段支持。 There is no setter; 没有制定者; any assignments performed in the constructor write directly to the fields. 在构造函数中执行的任何赋值都直接写入字段。

If your design makes you want to write to a read-only property via reflection, you should revisit your design :) 如果你的设计让你想通过反射写入只读属性,你应该重新审视你的设计:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM