有人可以解释我下面写的代码吗
public IList<GetProductPrice> CurrentPage
{
get { return ViewState["CurrentPage"] as List<GetProductPrice>; }
set { ViewState["CurrentPage"] = value; }
}
它被称为属性。它们在编译时生成 getter 和 setter 函数:
List<GetProductPrice> GetCurrentPage(){
return ViewState["CurrentPage"] as List<GetProductPrice>;
}
void SetCurrentPage(List<GetProductPrice> value) {
ViewState["CurrentPage"] = value;
}
//i think its actual get_.. but it doesn't matter for the example
因此,它生成了易于使用的 getter setter。您可以使用以下方法调用:
var test = CurrentPage; //compiled to var test = GetCurrenctPage();
CurrentPage = test; //compiled to SetCurrentPage(test);
如果您像这样将 getter 和 setter 留空:
public int CurrentPage
{
get;
set;
}
它还将在存储数据的类上生成一个支持字段:
private int _currentPage;
public GetCurrentPage(){ return _currentPage }
public SetCurrentPage(int value) { _currentPage = value }
使用 getter 和 setter 是来自 java 的一个非常古老的最佳实践(ide 可以选择生成它们)。但这会导致大量样板代码!
在 C# 中,他们试图通过添加这些属性来解决这个问题。但是为什么我们需要 getter 和 setter 呢?例如,如果您想在值更改时收到通知(将其自身标记为脏类)。我认为实体框架使用它来跟踪模型是否发生更改,否则它不会进行数据库更新调用。还有其他有用的工具可以在编译时在属性中注入代码。添加额外的功能。
使用属性返回HttpContext.Current
是危险的,因为你暗中依赖,HttpContext
所以任何时候都尽量不要这样做!
通常,当 get 或 set 中的代码非常繁重(非常密集)时,使用它也是不好的做法。这是不好的做法,因为使用该代码的其他人可能认为他只是设置了一个属性/字段,而实际上执行了一些非常繁重的代码。最好的做法是为此创建一个特殊的函数并私有 getter/setter:
public int Property {get; private set; }
public SetProperty(int value){
//intensive code here:
Property = value;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句