Вопрос

I have the following class, that has too many parameters in the constructor, and I want to refactor the class to receive only one object that encapsulate all the parameters.

public class MyClass
{
    public MyClass(
       string param1,
       string param2,
       string param3,
       string param4,
       string param5)
    {
       ...
    }
}

Is it possible to use Visual Studio refactor utility to encapsulate all the constructor parameters in a new class?

public class MyClass
{
    public MyClass(MyClassParameters parameters)
    {
       ...
    }
}

public class MyClassParameters
{
    public string Param1 { get; set; }
    public string Param2 { get; set; }
    public string Param3 { get; set; }
    public string Param4 { get; set; }
    public string Param5 { get; set; }
}

So my questions are

  • Can I do this using Visual Studio, so I don't have to manually update all the refereces to class MyClass?
  • Are there other refactor tools that support this functionality, such as Resharper, or others?

It is a hard work, since I have thousands of references to this class in my unit testing suite.

Это было полезно?

Решение

Do you have ReSharper?
With ReSharper you set cursor on constructor, press Ctrl+R, Ctrl+R and select Extract Class From Parameters....

Другие советы

The built in C# refactoring options do not include the "introduce parameter object" refactoring.

Resharper and Refactor Pro (both commercial) do have it.

If the class is being used all over the place already, what you can do is just create another constructor taking the MyParameter parameter, copy over the old functionality (updating the references to each parameter to the MyParameter properties/fields), and just have the old constructor read:

public MyClass(
   string param1,
   string param2,
   string param3,
   string param4,
   string param5) : this(new MyParameter(param1, param2...))
{
}

Not the prettiest solution, but as Oded mentions, there's no "built-in" way to refactor constructor parameters.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top