不可修改的变量 [英] variable that can't be modified
本文介绍了不可修改的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C#是否允许使用无法修改的变量?就像 const
,但是不必在声明时给它赋值,该变量没有任何默认值,而只能在运行时赋值一次(编辑:可能不是从构造函数)。还是不可能?
Does C# allow a variable that can't be modified? It's like a const
, but instead of having to assign it a value at declaration, the variable does not have any default value, but can only be assigned a value once at runtime ( and possibly not from constructor). or is this not possible?
推荐答案
您可以创建自己的提供此类功能的泛型类,但这可能会显得过大。 / p>
You could create your own generic class that provided this functionality, but that might be overkill.
public class SetValueOnce<T>
{
public bool _set;
private T _value;
public SetValueOnce()
{
_value = default(T);
_set = false;
}
public SetValueOnce(T value)
{
_value = value;
_set = true;
}
public T Value
{
get
{
if(!_set)
throw new Exception("Value has not been set yet!");
return _value;
{
set
{
if(_set)
throw new Exception("Value already set!");
_value = value;
_set = true;
}
}
}
这篇关于不可修改的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文