有什么方法可以简化重复的getter吗?

问题描述 投票:0回答:1

我有一个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

有没有更好的方法?比如自定义注解,自动创建这些近似的getter和setter?

c# getter-setter getter
1个回答
0
投票

我建议这样做。

public string variable1
{
    get { _variable1 = _variable1 ?? compute("some_data"); return _variable1; }
    set { _variable1 = value; }
}
© www.soinside.com 2019 - 2024. All rights reserved.