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

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

问题描述

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

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 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:属性名称"似乎完全无用且愚蠢.糟糕的程序员!考虑用方法替换.

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.

是否有现实生活中只写属性的例子,它们要么不能被直接的方法调用取代,要么会变得不那么直观?

推荐答案

只写属性实际上非常有用,我经常使用它们.这完全是关于封装 —— 限制对对象组件的访问.您经常需要为需要在内部使用的类提供一个或多个组件,但没有理由让其他类可以访问它们.这样做只会让您的类更加混乱(我是使用这个 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天全站免登陆