当我忘记分配String.Replace()时,可以使Visual Studio警告我吗? [英] Can I make Visual Studio warn me when I forget to assign String.Replace()?
问题描述
我只是编写了以下C#代码行,然后在程序无法按预期工作时花了几分钟的时间进行故障排除:
I just wrote the following line of C# code, and then spent a couple of minutes troubleshooting when the program didn't work as expected:
myString.Replace(oldValue, newValue);
( myString
, oldValue
和 newValue
都是字符串变量.)
(myString
, oldValue
, and newValue
are all string variables.)
很显然,我的意图是要使 myString
变量重新分配一个新字符串,该字符串等于原始 myString
值,但带有 oldValue
子字符串替换为 newValue
.
Obviously my intent was to cause the myString
variable to be reassigned a new string equal to the original myString
value but with the oldValue
substring replaced by newValue
.
同样很明显(事后看来),该行代码行不通,因为我应该将 Replace()
的返回值分配回 myString:
>
Equally obviously (in hindsight), that line of code didn't work because I should have assigned the return value of Replace()
back to myString:
myString = myString.Replace(oldValue, newValue);
尽管我很清楚C#字符串是不可变的,因此编写了诸如 Replace()
之类的方法以返回新的字符串实例,但我仍然发现自己不小心在编写诸如原始行之类的错误代码上面的代码.
Even though I'm well aware that C# strings are immutable and therefore methods like Replace()
are written to return a new string instance, I still find myself accidentally writing bad code like the original line of code above on occasion.
我的问题是:在这种情况下,我可以让Visual Studio给我一个编译时警告,以免我在运行时手动查找和诊断问题吗?
My question is: Can I get Visual Studio to give me a compile-time warning in this situation, to save me from needing to manually find and diagnose the problem at runtime?
请注意,由于我在此处使用.Net框架方法(String.Replace),因此请重写所讨论的方法以使用 out
参数(如
Note that since I'm using a .Net framework method here (String.Replace), rewriting the method in question to use an out
parameter (as in this similar question) isn't really an option.
推荐答案
您可以使用ReSharper,当您不将返回值分配给时,它会向您发出警告,指示您正在忽略方法的返回值.变量.
You can use ReSharper, it will give you a warning indicating that you are ignoring the return value from a method, when you don't assign the return value to a variable.
这篇关于当我忘记分配String.Replace()时,可以使Visual Studio警告我吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!