Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

oop - Do write-only properties have practical applications?

I don't know why I started thinking about this, but now I can't seem to stop.

In C# - and probably a lot of other languages, I remember that Delphi used to let you do this too - it's legal to write this syntax:

class WeirdClass
{
    private void Hello(string name)
    {
        Console.WriteLine("Hello, {0}!", name);
    }

    public string Name
    {
        set { Hello(name); }
    }
}

In other words, the property has a setter but no getter, it's write-only.

I guess I can't think of any reason why this should be illegal, but I've never actually seen it in the wild, and I've seen some pretty brilliant/horrifying code in the wild. It seems like a code smell; it seems like the compiler should be giving me a warning:

CS83417: Property 'Name' appears to be completely useless and stupid. Bad programmer! Consider replacing with a method.

But maybe I just haven't been doing this long enough, or have been working in too narrow a field to see any examples of the effective use of such a construct.

Are there real-life examples of write-only properties that either cannot be replaced by straight method calls or would become less intuitive?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Code Analysis (aka FxCop) does give you a diagnostic:

CA1044 : Microsoft.Design : Because property 'WeirdClass.Name' is write-only, either add a property getter with an accessibility that is greater than or equal to its setter or convert this property into a method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...