[英]How to have a C# readonly feature but not limited to constructor?
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; }
}
您可以使用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...
}
只有在第一次调用Foo属性时才会调用GetFoo
。
这被称为埃菲尔的“曾经”特征。 这是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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.