Different Refactoring style for field encapsulatio

2019-07-07 03:50发布

When one choose Refactoring, Encapsulate Fields for let's say:

int m_member;

VS will generate

    public int Member
    {
        get { return m_member; }
        set { m_member = value; }
    }

For some reason (using a reverse engineerint tool for example which doesn't know this style), I'd like to get the oldish and more verbose style:

    public int getMember() {
        return m_member;
    }

    public void setMember(int value) {
        m_member = value;
    }

Is it possible to configure VS to do so ? Otherwise any other mean with sample code like creating snippet template or even Plugin if necessary ?

3条回答
唯我独甜
2楼-- · 2019-07-07 04:21

So... you want to write Java/C++/(any language that doesn't support properties) in C#? Why?

Properties are nice because:

  1. Syntax is cleaner.
  2. Debugging is easier (you can see the value in the debugger as if the property were a field).
  3. It is idiomatic. C# developers will furrow their brow at you when they look at your code. Yes, this does sometimes matter, and it certainly matters if you are not the sole developer working on this project.

Even your method naming convention looks like Java. It is a good idea to get into the habit of adopting the idioms of a new language as you learn it.

查看更多
淡お忘
3楼-- · 2019-07-07 04:26

This pattern is not idiomatic of C# code - and Visual Studio doesn't support it. I would recommend avoiding it in favor of the property syntax. However, if you really do need it for some reason, you can get there with ReSharper. Here's what you do in ReSharper:

  1. Refactor >> Encapsulate Field (this creates a property)
  2. Refactor >> Convert >> Property To Method(s) (this generates the get/set methods)

The first step let's you create a property that wraps the public field.

The second replaces that property with get/set methods whose names you can specify.

查看更多
Emotional °昔
4楼-- · 2019-07-07 04:32

Although I don't necessarily recommend this, all refactorings are simply snippets that you can edit. A default installation will put the C# templates in this folder, C:\Program Files\Microsoft Visual Studio 10.0\VC#\Snippets\1033\Refactoring, simply find the one that you want and modify as you see fit.

NOTE: Be sure to take a backup first!!

I'll also agree with everyone else, that this is a REALLY bad idea!

查看更多
登录 后发表回答