Why using only setter in property declaration?

后端 未结 4 578
北荒
北荒 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.

    0 讨论(0)
  • 2021-01-26 09:49

    It doesn't make a whole lot of sense to have an auto-property with only a setter. It can make sense to have a manually implemented property with only a setter that can then set a field used internally, but not visible externally.

    Having a set only property is very uncommon, and are often implemented with a set method instead of a property as a set-only property is not expected behavior for most developers.

    In fact, it is a compiler error for an auto-implemented property to define a set without a get. A set-only property must be manually defined.

    0 讨论(0)
  • 2021-01-26 09:56

    A method would make much more sense than a 'write only property' - even if the code did compile. There is an interesting discussion around write only proprties Here

    0 讨论(0)
  • 2021-01-26 10:12

    You normally don't create a property like this. As you say, it doesn't have much value.

    If you really want to allow only setting a certain value without reading it, then provide a method. That's cleaner.

    0 讨论(0)
提交回复
热议问题