是否可以有只能分配一次的字段? [英] Is it possible to have fields that are assignable only once?
问题描述
我需要一个可以从任何我想要的地方分配到的字段,但应该只能分配一次(因此应忽略后续分配).我该怎么做?
I need a field that can be assigned to from where ever I want, but it should be possible to assign it only once (so subsequent assignments should be ignored). How can I do this?
推荐答案
那时那将不是只读字段.初始化真正的只读字段的唯一选项是字段初始值设定项和构造函数.
That would not be a readonly field then. Your only options for initializing real readonly fields are field initializer and constructor.
然而,您可以使用属性实现一种只读功能.将您的字段设为属性.实现一个冻结实例"方法,该方法翻转一个标志,说明不允许对只读部分进行更多更新.让你的二传手检查这个标志.
You could however implement a kind of readonly functionality using properties. Make your field as properties. Implement a "freeze instance" method that flipped a flag stating that no more updates to the readonly parts are allowed. Have your setters check this flag.
请记住,您正在放弃编译时检查以进行运行时检查.编译器会告诉您是否尝试从声明/构造函数以外的任何地方为只读字段赋值.使用下面的代码,您会得到一个异常(或者您可以忽略更新 - 两者都不是最佳的 IMO).
Keep in mind that you're giving up a compile time check for a runtime check. The compiler will tell you if you try to assign a value to a readonly field from anywhere but the declaration/constructor. With the code below you'll get an exception (or you could ignore the update - neither of which are optimal IMO).
为了避免重复检查,您可以将只读功能封装在一个类中.
to avoid repeating the check you can encapsulate the readonly feature in a class.
修订后的实现可能如下所示:
Revised implementation could look something like this:
class ReadOnlyField<T> {
public T Value {
get { return _Value; }
set {
if (Frozen) throw new InvalidOperationException();
_Value = value;
}
}
private T _Value;
private bool Frozen;
public void Freeze() {
Frozen = true;
}
}
class Foo {
public readonly ReadOnlyField<int> FakeReadOnly = new ReadOnlyField<int>();
// forward to allow freeze of multiple fields
public void Freeze() {
FakeReadOnly.Freeze();
}
}
然后你的代码可以做类似的事情
Then your code can do something like
var f = new Foo();
f.FakeReadOnly.Value = 42;
f.Freeze();
f.FakeReadOnly.Value = 1337;
最后一条语句会抛出异常.
The last statement will throw an exception.
这篇关于是否可以有只能分配一次的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!