gpt4 book ai didi

c# - 通过反射设置自动属性的值

转载 作者:行者123 更新时间:2023-11-30 14:52:38 25 4
gpt4 key购买 nike

我看过各种关于如何通过反射调用属性的私有(private) setter 的线程。但是,如果没有 setter 的自动属性呢?

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

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

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

有什么想法吗?

最佳答案

Is it possible to set the value of this readonly property using reflection?

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

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

关于c# - 通过反射设置自动属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31480933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com