gpt4 book ai didi

c# - 如何拥有 C# 只读功能但不限于构造函数?

转载 作者:太空狗 更新时间:2023-10-29 22:23:59 25 4
gpt4 key购买 nike

C#“只读”关键字是一个修饰符,当字段声明包含它时,对声明引入的字段的赋值只能作为声明的一部分或在同一类的构造函数中出现。

现在假设我确实想要这个“一次赋值”约束,但我宁愿允许赋值在构造函数之外完成,可能是延迟/延迟评估/初始化。

我该怎么做?是否有可能以一种很好的方式做到这一点,例如,是否可以编写一些属性来描述它?

最佳答案

如果我没有正确理解您的问题,听起来您只想设置一次字段值(第一次),之后不允许再设置。如果是这样,那么之前所有关于使用 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# - 如何拥有 C# 只读功能但不限于构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8088491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com