Why using only setter in property declaration?

后端 未结 4 581
北荒
北荒 2021-01-26 09:32
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 t

4条回答
  •  遥遥无期
    2021-01-26 09:49

    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 and XmlTextReader.XmlResolver are probably write-only properties for the same reason.

    (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.

    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.

提交回复
热议问题