如何反复告知属性是否具有公共Setter
我将对象模型保存到XML但是当我将其加载回来时,我在尝试使用PropertyInfo.SetValue()时会遇到exception,因为该属性没有setter只是一个getter。
我想要么不保存只有getter的属性或者在加载时弄清楚它是否适合我尝试设置值。
任何人都知道如何做到这一点
干杯
您可以使用PropertyInfo.GetSetMethod
– 如果属性是只读的或者setter是非公共的,则返回null
。
if (property.GetSetMethod() != null) { // Yup, you can write to it. }
如果您可以应对非公开制定者,您可以使用:
if (property.GetSetMethod(true) != null) { // Yup, there's a setter - but it may be private }
使用PropertyInfo.CanWrite属性。