如何使用Resharper结构查找和替换将C#对象初始值设定项转换为使用构造函数

Chr*_*ook 5 c# resharper structural-search

我想使用Resharper结构搜索和替换模板来自动替换此示例:

new Fruit { Name = "Apple", IsTasty = true }

有了这个:

new Fruit("Apple", true)

(注意,所需的构造函数已存在)

我尝试过这样的各种组合:

new $type$ { Name = $name$, IsTasty = $isTasty$ };

...使用各种不同的占位符类型,但R#在我的代码中找不到任何示例.有没有人这样做过?

pms*_*969 6

所以我只是在resharper中做到了这一点(我觉得9.0.2)

创建模式:FruityChange

  • new $ type $ {Name = $ param1 $,IsTasty = $ param2 $}
  • $ type $是一种类型
  • $ param1 $是string类型的表达式
  • $ param2 $是bool类型的表达式
  • 模式严重性"显示为错误"

与类水果

public class Fruit
{
    public Fruit(string name, bool isTasty)
    {
        Name = name;
        IsTasty = isTasty;
    }

    public string Name { get; set; }
    public bool IsTasty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并强调了代码编辑器中的表达式,alt-tab为我提供了"替换为"选项.它至少适用于我的机器:-)