有没有一种方法可以简化重复的吸气剂?

时间:2020-06-11 01:40:57

标签: c# getter-setter getter

我有一个带有许多变量的c#类,所有变量都初始化为null。首次访问时,我想计算它们的值并将其返回(存储该值以加快将来的访问速度)。为此,我编写了类似

的代码
private T nullCheck<T>(T value, string how_to_compute) {
    if (value == null) {
        return compute(how_to_compute);
    }
    return value;
}

private string _variable1
public string variable1 {
    get { _variable1 = nullCheck(_variable1, "someData"); return _variable1; }
    set { _variable1 = value; }
}

...

每个变量的代码与variable1

类似

有更好的方法吗?就像自定义注释会自动创建这些几乎相同的吸气剂和吸气剂一样?

1 个答案:

答案 0 :(得分:0)

我建议做这样的事情:

public string variable1
{
    get { _variable1 = _variable1 ?? compute("some_data"); return _variable1; }
    set { _variable1 = value; }
}