我应该用设置一次变量? [英] Should I use set once variables?

查看:122
本文介绍了我应该用设置一次变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是否臭?结果
我中有你只能设置一次几个属性。他们可以在对象存续期间的任何时间进行设置,不能撤消。结果
我实现再这样。

Does this smell?
I have a few properties you can only set once. They can be set at any time during the objects existence and can not be undone.
I implement then like this.

    private FooThingy _foo;
    public FooThingy Foo
    {
        set { if (null == _foo) _foo = value; }
        get { return _foo; }
    }



但我不喜欢它。我觉得我错过了一些东西。我有

But I don't like it. I feel like I have missed something. Have I?

修改:为什么我没有它在构造函数中。
结果我不能进入细节,但设置这将导致 < 坏的比喻> 熔蜡雕像 < /坏的比喻> 。而且我不希望我的构造函数创建已经融化的对象。

Edit: Why I don't have it in the constructor.
I cant go into the details but setting this results in <bad analogy> Melting the wax statue </bad analogy>. And I don't want my constructor to create already melted objects.

推荐答案

设置一次的属性违反了最小惊讶的原则 - 来电者预计,当属性可以被设置一次,它可以被重新设置。 (禁止范围和兼容性检查,当然 - 但它们绑定到特定值或值组合)。

Set-once-properties violate the principle of least surprise - a caller expects that when a property can be set once, it can be set again. (barring range and compatibility checks, of course - but they are bound to specific values or value combinations).

在构造函数初始化它们。

或者,如果他们要多/复杂写所有的构造,使用工厂/生成器类

Initialize them in the constructor.
Alternatively, if they are to many / to complex to write all constructors, use a factory/builder class:

ThingieBuilder tb = new ThingieBuilder();
tb.FooThingy = 17.23;   // r/w properties
tb.BarThingy = 42;
tb.UseExtendedThingamagicAdapter = true;
Thingie t = tb.Create();
if (t.Bar==42) // r/o property
  ...

或者,分开在配置对象的设置,可被取代或施工过程中传递

Or, separate the settings in a configuration object, that can be replaced or passed during construction.

这篇关于我应该用设置一次变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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