我可以在 C# 中自动生成我的 get/set 方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1675023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:53:37  来源:igfitidea点击:

Can I auto-generate my get/set methods in c#?

c#

提问by NibblyPig

Takes -ages- by hand. Can I not just select my properties and click a button?

需要 -age- 手工。我不能只选择我的属性并单击一个按钮吗?

They look like this:

它们看起来像这样:

private bool _Monday = false;
private bool _Tuesday = false;
private bool _Wednesday = false;
private bool _Thursday = false;
private bool _Friday = false;
private bool _Saturday = false;
private bool _Sunday = false;

and there are LOADS of them.

他们有很多。

采纳答案by Konrad Rudolph

The current version of C# (3.0) has auto properties:

当前版本的 C# (3.0) 具有自动属性:

public bool Monday { get; set; }
// etc …

(You don't need your fields now, backing fields are generated by the compiler.) Unfortunately, they do not support (yet) initialization expressions – but in your example you don't need them since falseis the default value for bools anyway.

(您现在不需要您的字段,支持字段由编译器生成。)不幸的是,它们不支持(尚未)初始化表达式 - 但在您的示例中,您不需要它们,因为无论如何false都是bools的默认值。

回答by Ryan Brunner

Some plugins to Visual Studio have functionality for creation of properties based on private fields (ReSharperis a good example).

Visual Studio 的一些插件具有基于私有字段创建属性的功能(ReSharper就是一个很好的例子)。

回答by Kevin

We use code snippetsthat allow us to provide the datatype and property name on the fly. We also have the option of providing a OnPropertyChanged event.

我们使用允许我们动态提供数据类型和属性名称的代码片段。我们还可以选择提供 OnPropertyChanged 事件。

回答by Rex M

You can right-clickon the field and go to Refactor > Encapsulate Field. That will generate a Property. You still have to do each one at a time but it's a lot faster than the typing!

您可以右键单击该字段并转到Refactor > Encapsulate Field。这将生成一个属性。您仍然必须一次完成每一项,但这比打字快得多!

回答by GraemeF

You can use automatic propertieswith C# 3.0 or later:

您可以在 C# 3.0 或更高版本中使用自动属性

public bool Monday { get; set; }

Is roughly equivalent to:

大致相当于:

private bool _Monday;
public bool Monday
{
    get { return _Monday; }
    set { _Monday = value; }
}

回答by Matt Brunell

Ctrl+K, Ctrl+X opens up code snippets. Type 'prop' for a property declaration code snippet. You can tab through the snippet fields and fill them in. Hit enter to complete the snippet.

Ctrl+K、Ctrl+X 打开代码片段。为属性声明代码片段键入“prop”。您可以通过 Tab 键浏览代码段字段并填写它们。按 Enter 键以完成代码段。

回答by Hannoun Yassir

if you use visual studio just type prop then press tab and visual studio will let you chose the type and name of the property

如果您使用 Visual Studio 只需键入 prop 然后按 Tab 键,Visual Studio 将让您选择属性的类型和名称