我想选择代码,例如
doSomething(myEnum.firstThing)
doSomethingElse(myEnum.firstThing)
evenMoreStuff(myEnum.firstThing)
并将其转换为函数
GroupCommonStuf(myEnum.firstThing)
看起来像是这样的:
GroupCommonStuff(myEnum id)
{
doSomething(id)
doSomethingElse(id)
evenMoreStuff(id)
}
最好它会捕获任何代码:
doSomething(myEnum.secondThing)
doSomethingElse(myEnum.secondThing)
evenMoreStuff(myEnum.secondThing)
并将其转换为
GroupCommonStuf(myEnum.secondThing)
等等
我安装了ReSharper。但是ReSharper中的extract方法似乎只提取了我选择的代码块。它不会传播其他“类似代码”,我相信Eclipse会为C ++和Java做。
我假设我也可以通过正则表达式来实现这一点,但我还不是正则表达式。我怎样才能做到这一点?
使用三个有用的ReSharper工具可以分三步完成:
没有ReSharper的可能替代方案位于底部
GroupCommonStuf()
{
doSomething(myEnum.firstThing)
doSomethingElse(myEnum.firstThing)
evenMoreStuff(myEnum.firstThing)
}
GroupCommonStuf(myEnum type)
{
doSomething(type)
doSomethingElse(type)
evenMoreStuff(type)
}
doSomething(myEnum.firstThing);
doSomethingElse(myEnum.firstThing);
evenMoreStuff(myEnum.firstThing);
将被取代
GroupCommonStuf(myEnum.firstThing)
对于enum :)的任何变化都是一样的。关于这里发生了什么的一些解释
简而言之,ReSharper在()之间找到任何参数并将它们存储在变量“enumeration”中(名称实际上并不重要)。然后在变量块中出现变量的任何位置插入该字符串。
有不同的placeholders做不同的事情,使用正确的... = GetGraphic(Graphics.First).ShapeArray[index].ShapeColour
... = GetGraphic(Graphics.Second).ShapeArray[index].ShapeSize
... = GetGraphic(Graphics.First).ShapeArray[index].ShapeSize
很重要。 “type”占位符甚至支持正则表达式,这使得它非常强大。
在这种情况下,您可以简单地键入$ enumeration $,因为默认占位符是“arguments”。但是我会建议养成使用“添加占位符”的习惯,因为当你执行更复杂的模式时它会更清晰。重要的是你知道它不仅仅是“将字符串置于变量中”。
为了更好地解释这个,请考虑这个例子,假设你有以下代码:
... = GetShapeColour(Graphics.First, index);
... = GetShapeSize(Graphics.Second, index);
... = GetShapeSize(Graphics.First, index);
而且你决定用更类似的代码替换所有这些代码
Shape*
通过使用正确的占位符,您可以通过一次搜索和替换来执行此操作:
如果你曾为“variableOfArray”使用“参数占位符”,那么Resharper就会说它找不到任何模式,因为没有GetGraphic(..)。ShapeArray [index]。(..)这样的东西。
没有ReSharper的可能的解决方法:
提取到方法→Extract Method Refactoring
使用/不使用Promote Variable To Parameter引入参数→“查找替换”
使用模式搜索→这对我来说显然是很难的,有三个选项我不想特别探索,我的猜测通常需要更多的时间才能手动进行更改: