为什么在属性声明中仅使用setter? [英] Why using only setter in property declaration?

查看:44
本文介绍了为什么在属性声明中仅使用setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int MyProperty { set; }

仅对属性使用二传手的想法是什么?如果我们将一个属性设置为某个值,我想很可能会在某个时候读取该值?

What's the idea for using only setter on property? If we set one property with some value, I guess it's very likely to read this value at some point ?

推荐答案

纯写属性在基类库中很少见,但

Write-only properties are rare in the Base Class Library, but XmlReaderSettings.XmlResolver is one example. Based on the security note in that topic, I believe the get accessor was omitted to prevent partially trusted code from accessing or tampering with the default resolver.

XmlResolver.Credentials XmlTextReader.XmlResolver 可能是相同的原因.

XmlResolver.Credentials and XmlTextReader.XmlResolver are probably write-only properties for the same reason.

(奇怪的是, XmlAttribute.InnerText 也是一个只写属性,但这似乎不是一个好的设计.)

(Strangely, XmlAttribute.InnerText is also a write-only property, but this doesn't seem to be good design.)

在上面的示例之后,我想您应该在仅使用读写属性的情况下使用只写属性,但是您不希望获取访问器来确保安全性原因.

Following the above examples, I'd say you should use a write-only property only when a read-write property would otherwise make sense, but you don't want a get accessor for security reasons.

您当然可以改用 Set 方法,但是属性具有可以在对象初始化程序中使用的优点,这与 XmlReaderSettings 一样.

You could of course use a Set method instead, but a property has the advantage that it can be used in an object initializer, as is commonly done with XmlReaderSettings.

这篇关于为什么在属性声明中仅使用setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆