C#“readonly”关键字是一个修饰符,当字段声明包含它时,对声明引入的字段的赋值只能作为声明的一部分或在同一类的构造函数中发生。
现在假设我确实想要这个“一次赋值”约束,但我宁愿允许在构造函数之外完成赋值,可能是延迟/延迟评估/初始化。
我怎么能那样做?是否有可能以一种很好的方式做到这一点,例如,是否可以编写一些属性来描述这一点?
C#“readonly”关键字是一个修饰符,当字段声明包含它时,对声明引入的字段的赋值只能作为声明的一部分或在同一类的构造函数中发生。
现在假设我确实想要这个“一次赋值”约束,但我宁愿允许在构造函数之外完成赋值,可能是延迟/延迟评估/初始化。
我怎么能那样做?是否有可能以一种很好的方式做到这一点,例如,是否可以编写一些属性来描述这一点?
如果我正确理解您的问题,听起来您只想设置一次字段的值(第一次),然后不允许设置它。如果是这样,那么之前所有关于使用 Lazy(和相关)的帖子都可能有用。但是,如果您不想使用这些建议,也许您可以执行以下操作:
public class SetOnce<T>
{
private T mySetOnceField;
private bool isSet;
// used to determine if the value for
// this SetOnce object has already been set.
public bool IsSet
{
get { return isSet; }
}
// return true if this is the initial set,
// return false if this is after the initial set.
// alternatively, you could make it be a void method
// which would throw an exception upon any invocation after the first.
public bool SetValue(T value)
{
// or you can make thread-safe with a lock..
if (IsSet)
{
return false; // or throw exception.
}
else
{
mySetOnceField = value;
return isSet = true;
}
}
public T GetValue()
{
// returns default value of T if not set.
// Or, check if not IsSet, throw exception.
return mySetOnceField;
}
} // end SetOnce
public class MyClass
{
private SetOnce<int> myReadonlyField = new SetOnce<int>();
public void DoSomething(int number)
{
// say this is where u want to FIRST set ur 'field'...
// u could check if it's been set before by it's return value (or catching the exception).
if (myReadOnlyField.SetValue(number))
{
// we just now initialized it for the first time...
// u could use the value: int myNumber = myReadOnlyField.GetValue();
}
else
{
// field has already been set before...
}
} // end DoSomething
} // end MyClass
现在假设我确实想要这个“赋值一次”约束,但我宁愿允许在构造函数之外完成赋值
请注意,延迟初始化很复杂,因此对于所有这些答案,如果您有多个线程试图访问您的对象,您应该小心。
如果你想在课堂上这样做
您可以使用 C# 4.0 内置的延迟初始化功能:
或者对于旧版本的 C#,只需提供一个get
方法,并使用支持字段检查您是否已经初始化:
public string SomeValue
{
get
{
// Note: Not thread safe...
if(someValue == null)
{
someValue = InitializeSomeValue(); // Todo: Implement
}
return someValue;
}
}
如果你想在课外这样做
你想要冰棒不变性:
基本上:
Freeze
方法。ModifyFrozenObjectException
.IsFrozen
.顺便说一句,我刚才编了这些名字。诚然,我的选择很差,但目前还没有普遍遵循的惯例。
现在我建议您创建一个IFreezable
接口,以及可能的相关异常,因此您不必依赖 WPF 实现。就像是:
public interface IFreezable
{
void Freeze();
bool IsFrozen { get; }
}
这在 Eiffel 中被称为“一次”功能。这是 C# 中的一个重大疏忽。新的 Lazy 类型是一个糟糕的替代品,因为它不能与其非惰性版本互换,而是要求您通过其 Value 属性访问包含的值。因此,我很少使用它。噪音是 C# 代码的最大问题之一。理想情况下,一个人想要这样的东西......
public once Type PropertyName { get { /* generate and return value */ } }
与当前的最佳实践相反...
Type _PropertyName; //where type is a class or nullable structure
public Type PropertyName
{
get
{
if (_PropertyName == null)
_PropertyName = /* generate and return value */
return _PropertyName
}
}
您可以使用Lazy<T>
该类:
private readonly Lazy<Foo> _foo = new Lazy<Foo>(GetFoo);
public Foo Foo
{
get { return _foo.Value; }
}
private static Foo GetFoo()
{
// somehow create a Foo...
}
GetFoo
只会在您第一次调用 Foo 属性时调用。