How can we generate getters and setters in Visual Studio?

后端 未结 16 2118
盖世英雄少女心
盖世英雄少女心 2020-12-07 07:46

By \"generate\", I mean auto-generation of the code necessary for a particular selected (set of) variable(s).

But any more explicit explication or comment on good pr

相关标签:
16条回答
  • 2020-12-07 08:16

    Visual Studio also has a feature that will generate a Property from a private variable.

    If you right-click on a variable, in the context menu that pops up, click on the "Refactor" item, and then choose Encapsulate Field.... This will create a getter/setter property for a variable.

    I'm not too big a fan of this technique as it is a little bit awkward to use if you have to create a lot of getters/setters, and it puts the property directly below the private field, which bugs me, because I usually have all of my private fields grouped together, and this Visual Studio feature breaks my class' formatting.

    0 讨论(0)
  • 2020-12-07 08:18

    In addition to the 'prop' snippet and auto-properties, there is a refactor option to let you select an existing field and expose it via a property (right click on the field → Refactor → Encapsulate Field...).

    Also, if you don't like the 'prop' implementation, you can create your own snippets. Additionally, a third-party refactoring tool like ReSharper will give you even more features and make it easier to create more advanced snippets. I'd recommend ReSharper if you can afford it.

    • http://msdn.microsoft.com/en-us/library/f7d3wz0k(VS.80).aspx

    • Video demonstrating the use of snippet 'prop' (among other things), at 3 min 23 secs.

    0 讨论(0)
  • 2020-12-07 08:18

    On behalf of the Visual Studio tool, we can easily generate C# properties using an online tool called C# property generator.

    0 讨论(0)
  • 2020-12-07 08:19

    If you are using Visual Studio 2005 and up, you can create a setter/getter real fast using the insert snippet command.

    Right click on your code, click on Insert Snippet (Ctrl+K,X), and then choose "prop" from the list.

    0 讨论(0)
提交回复
热议问题