且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# 中的不可变对象模式 - 你怎么看?

更新时间:2023-10-14 19:38:10

有关信息,第二种方法称为冰棒不变性".

For info, the second approach is called "popsicle immutability".

Eric Lippert 有一系列关于不变性的博客条目,从 此处.我仍在掌握 CTP (C# 4.0),但它看起来很有趣可选/命名参数(对 .ctor)可能在这里做什么(当映射到只读字段时)......[更新:我在这个这里上写了博客]

Eric Lippert has a series of blog entries on immutability starting here. I'm still getting to grips with the CTP (C# 4.0), but it looks interesting what optional / named parameters (to the .ctor) might do here (when mapped to readonly fields)... [update: I've blogged on this here]

有关信息,我可能不会将这些方法设为 virtual - 我们可能不希望子类能够使其不可冻结.如果您希望他们能够添加额外的代码,我建议您这样做:

For info, I probably wouldn't make those methods virtual - we probably don't want subclasses being able to make it non-freezable. If you want them to be able to add extra code, I'd suggest something like:

[public|protected] void Freeze()
{
    if(!frozen)
    {
        frozen = true;
        OnFrozen();
    }
}
protected virtual void OnFrozen() {} // subclass can add code here.

此外 - AOP(例如 PostSharp)可能是添加所有 ThrowIfFrozen() 检查的可行选项.

Also - AOP (such as PostSharp) might be a viable option for adding all those ThrowIfFrozen() checks.

(抱歉,如果我更改了术语/方法名称 - 因此在撰写回复时不会保持原始帖子可见)

(apologies if I have changed terminology / method names - SO doesn't keep the original post visible when composing replies)