在visual studio中找到所有与==的比较

我犯了错误,使用==来比较IP地址,而不是使用C#中IPAddress类的equals()方法,这将导致引用而不是值的比较。 由于我目前正在处理的解决方案对于单人项目(> 100.000行源代码)而言非常大,我非常确定我的代码中仍然存在一些错误的语句。

有没有可能告诉Visual Studio为我查找特定类的所有==操作,以便我可以找到并清理错误的比较?

最诚挚的问候,emi

这有点像黑客,但您可以暂时将此类添加到您的项目中:

 namespace System.Net { class IPAddress { [Obsolete] public static bool operator ==(IPAddress a, IPAddress b) { return true; } [Obsolete] public static bool operator !=(IPAddress a, IPAddress b) { return true; } } } 

编译并查找有关使用过时方法的警告:

警告'IPAddress.operator ==(IPAddress,IPAddress)'已过时

修复代码后,删除类定义。

您总是可以在“==”上使用查找/替换。 您可以使用filter来确定要搜索的内容/位置,或者只使用整个解决方案。

您可以使用.NET Reflector或Visual Studio调用层次结构窗口来查找对IPAdress类的operator ==方法的调用。 我不知道这是否可能,只是抛出一个想法。

如果您知道代码中代表IP地址的变量的名称,那么可以使用一些解决方法。 假设您的变量名为’ipAddress’。 然后这样做:

使用通配符搜索:

 ipAddress*== 

然后遍历结果并制作一个宏,为您做出改变。 例如,假设您的语句如下所示:

 if (ipAddress == anotherIpAddress) { 

然后你做一个微观如下:

 Start Recording Press Home # This will go to the beginning of the line Ctrl+Right Three Times # This will keep the cursor on the beginning of anotherIpAddress Backspace # This will remove the space .equals( # This will write .equals( Del Three Times # This will delete the == and the space after it Ctrl+Right # This will keep you at the closing bracket ). ) # This will write another closing bracket for the equals functions. Stop Recording 

现在你有了一个宏来改变你的行。 您所要做的就是反复按F4然后按Ctrl ^ P. 按F4将您移动到文件中查找的下一个结果(我想你将使用它),然后按Ctrl ^ P执行宏。

有一个更好的解决方案实际上使用正则表达式,但我不确定它是否适用于visual studio。 基本上,它将Find中的元素分组并在Replace中使用它们。 所以你搜索类似“ipAddress ==()”的东西,并用“ipAddress.equals(\ 1)”替换它,这里的那个引用第一组。

希望有所帮助!

您可以inheritanceIPAddress并覆盖==运算符。 这当然取决于您可以轻松地替换参考文献。 一旦你完成了,你可以停在那里或用.Equals()替换你的==运算符的所有实例