只读属性是否有实际应用? [英] Do write-only properties have practical applications?

查看:73
本文介绍了只读属性是否有实际应用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么开始考虑这个问题,但是现在我似乎无法停止.

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

在C#中-可能还有许多其他语言,我记得Delphi曾经也允许您这样做-编写此语法是合法的:

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); }
    }
}

换句话说,该属性具有一个 setter ,但没有一个 getter ,它是只写的.

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 seem 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:属性名称"似乎完全没有用而且很愚蠢.不好的程序员!考虑用一种方法代替.

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 in order to see any examples of the effective use of such a construct.

是否存在现实生活中只写属性的示例,这些示例要么不能被直接方法调用所取代,要么会变得不那么直观?

推荐答案

仅写属性实际上非常有用,我经常使用它们.都是关于封装的操作-限制对对象组件的访问.您通常需要为需要在内部使用的类提供一个或多个组件,但是没有理由使它们可被其他类访问.这样做只会使您的类更加混乱(我使用此getter还是该方法?"),并且更有可能会篡改您的类或绕过其实际用途.

Write-only properties are actually quite useful, and I use them frequently. It's all about encapsulation -- restricting access to an object's components. You often need to provide one or more components to a class that it needs to use internally, but there's no reason to make them accessible to other classes. Doing so just makes your class more confusing ("do I use this getter or this method?"), and more likely that your class can be tampered with or have its real purpose bypassed.

请参见为什么getter和setter方法是邪恶的" 对此进行了有趣的讨论.我不像文章的作者那样刻骨铭心,但是我认为这是一件好事.我通常会使用setter,但很少使用getter.

See "Why getter and setter methods are evil" for an interesting discussion of this. I'm not quite as hardcore about it as the writer of the article, but I think it's a good thing to think about. I typically do use setters but rarely use getters.

这篇关于只读属性是否有实际应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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