为什么 VS 2017 会建议用方法替换属性? [英] Why would VS 2017 suggest replacing a property with a method?

查看:43
本文介绍了为什么 VS 2017 会建议用方法替换属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 Visual Studio 2017 中的每个属性都有一个快速操作,建议将其替换为方法.

I noticed that every property in Visual Studio 2017 has a quick action that suggests replacing it with a method.

这是否意味着属性不是设置和获取字段值的推荐方式,微软是否打算在未来弃用它?!

Is that mean that properties is not the recommended way to set and get fields value, do Microsoft intend to deprecate it in the future?!

或者,为此目的,使用方法而不是属性可以实现任何收益吗?

Or are there any gains that could be achieved using methods over properties for that purpose?

推荐答案

这不是来自 Visual Studio 的建议,而是一个 快速操作:

This is not a suggestion from Visual Studio, it is a Quick Action:

快速操作可让您通过单个操作轻松重构、生成或以其他方式修改代码.

Quick Actions let you easily refactor, generate, or otherwise modify code with a single action.

Visual Studio 为您提供了一个选项,可以将属性转换为一对方法和一个私有变量,作为代码重构的一部分,如果您出于各种原因希望这样做的话.

Visual Studio gives you an option to convert a property to a pair of methods and a private variable as part of code refactoring, should you wish to do so for a variety of reasons.

例如,您可能意识到 getter 应该接收一个额外的参数,或者 setter 应该对其他类型进行重载.在这些情况下,将需要一个方法而不是一个属性,因此 Visual Studio 为您提供了一种只需点击几下即可完成的方法.

For example, you may realize that a getter should receive an extra parameter, or the setter should have overloads on other types. In these situations a method would be required instead of a property, so Visual Studio offers you a way to do it in a few simple clicks.

对于没有任何行为的存储属性,例如类中的 OfferPeriod 属性,转换为一对方法不会比自动属性提供任何优势.

For stored properties that do not have any behavior, such as the OfferPeriod property in your class, conversion to a pair of methods does not offer any advantages over an automatic property.

这篇关于为什么 VS 2017 会建议用方法替换属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆