Pau*_*aul 216 c# getter setter visual-studio
通过"生成",我的意思是自动生成特定选择的(一组)变量所需的代码.
但欢迎任何更明确的解释或对良好做法的评论.
Dan*_*ert 51
Visual Studio还具有一个将从私有变量生成属性的功能.
如果右键单击变量,则在弹出的上下文菜单中单击"重构"项.然后选择封装字段.这将为变量创建getter/setter属性.
我不是太喜欢这种技术的粉丝,因为如果你必须创建很多getter/setter它会有点尴尬,并且它将属性直接放在私有字段下面,这会让我感到烦恼,因为我通常有我的所有私有字段组合在一起,这个Visual Studio功能打破了我的类的格式.
nhu*_*uvy 31
我使用Visual Studio 2013 Professional.

Refactor \ Encapsulate Field...然后按OK.
Preview Reference Changes - Encapsulate Fielddiaglog中,按下按钮Apply.

您还可以放置光标来选择属性,使用Menu Edit\Refactor\Encapsulate Field ...
和
private int productID;
public int ProductID
{
get { return productID; }
set { productID = value; }
}
Run Code Online (Sandbox Code Playgroud)
成为
public int ProductID { get; set; }
Run Code Online (Sandbox Code Playgroud)
Jon*_*jap 30
通过生成,你的意思是自动生成?如果这不是你的意思:
Visual Studio 2008具有最简单的实现:
public PropertyType PropertyName { get; set; }
Run Code Online (Sandbox Code Playgroud)
在后台,这将创建一个隐含的实例变量,您的属性将存储和检索到该变量.
但是,如果要在Properties中添加更多逻辑,则必须为其设置实例变量:
private PropertyType _property;
public PropertyType PropertyName
{
get
{
//logic here
return _property;
}
set
{
//logic here
_property = value;
}
}
Run Code Online (Sandbox Code Playgroud)
以前版本的Visual Studio也总是使用这种速记方法.
Adi*_*lik 11
在 Visual Studio 2019 中,像这样选择您的属性:
然后按Ctrl+r
然后按Ctrl+e
将出现一个对话框,显示您的代码将要发生的更改的预览。如果一切看起来都不错(大多数情况下都会如此),请按OK。
如果您使用的是Visual Studio 2005,则可以使用insert snippet命令快速创建setter/getter.右键单击代码,单击Insert Snippet(Ctrl+ k,x),然后从列表中选择"prop".希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
404842 次 |
| 最近记录: |