假设我有这样一个类:
public class MyClass {
...
public List<SomeClass> MyProperty {
get {
SomeClass.GetCollectionOfThese(someId);
}
}
...
}
GetCollectionOfThese()
调用数据库以检索构建集合所需的记录。现在假设我在其他地方有以下代码:
MyClass obj = new MyClass(someId);
List<SomeClass> temp = obj.MyProperty;
...
SomeClass otherObj = obj.MyProperty.FirstOrDefault(i => i.Foo == "bar");
在这种情况下,数据库是否被调用了两次?还是缓存在内存中的属性值?
最佳答案
您的实现将导致多个数据库调用。你必须做缓存,如果那是你需要的。像这样的东西:
public class MyClass {
...
private List<SomeClass> _myProperty = null;
public List<SomeClass> MyProperty {
get {
if (_myProperty == null) _myProperty = SomeClass.GetCollectionOfThese(someId);
return _myProperty;
}
}
...
}
当然,您可能希望为客户端提供刷新缓存的方法。
关于c# - 这个 getter 每次被引用时都会调用数据库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10458757/