Often 开发者_如何学运维I find myself coming across code like this:
try
{
StreamWriter strw = new StreamWriter();
}
However, there is no reference to the object outside the scope of the try block. How could I refactor (extract to field in Visual Studio says there is no field or something) the statement in the try block so that it is declared above the try block so I can use it anywhere in the method?
Thanks
You just need to split the declaration and assignment. If you have Resharper, there's a method to do the split, but you'll have to move it manually:
StreamWriter strw = null;
try
{
strw = new StreamWriter();
}
catch()
{ // ...
Often, adding the (technically useless) = null;
is required, as well, to prevent potential warnings about using variables before assignment, due to the assignment being in a different scope. This depends a bit on how you're using the data, though.
Also, since StreamWriter
is IDisposable, you'll want to make sure that you have a finally block that does the disposal, or place the the entire usage in a using
block.
StreamWriter strw = null;
try
{
strw = new StreamWriter();
}
But for a StreamWriter
(which is IDisposable
) it is even better to use the using
-keyword:
using( StreamWriter strw = new StreamWriter() )
{
..
}
精彩评论