我将一个对象模型保存到 XML,但是当我将它加载回时,我在尝试使用 PropertyInfo.SetValue() 时遇到异常,因为该属性没有 setter 只有 getter。
我想要么不保存只有 getter 的属性,要么在加载时弄清楚它是否对我尝试设置一个值有效。
谁知道怎么做
干杯
最佳答案
您可以使用 PropertyInfo.GetSetMethod
- 如果属性是只读的或者 setter 是非公共(public)的,这将返回 null
。
if (property.GetSetMethod() != null)
{
// Yup, you can write to it.
}
如果你能应付非公开的 setter,你可以使用:
if (property.GetSetMethod(true) != null)
{
// Yup, there's a setter - but it may be private
}
关于c# - 如何反射性地判断属性是否具有公共(public) Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2811198/