问题
I have this code, which I use all over my applications to save data back to the database.
public bool SaveDemo()
{
bool success = false;
try
{
using (DataTable dt = DataAccess.ExecuteDataTable("[dbo].[udp_Customers_ups]",
DataAccess.Parameter(CustomerIdColumn, CustomerId),
DataAccess.Parameter(CodeColumn, Code),
DataAccess.Parameter(CompanyColumn, Company),
DataAccess.Parameter(IsDeletedColumn, IsDeleted),
DataAccess.Parameter(LastUpdatedColumn, LastUpdated),
DataAccess.Parameter(UpdatedByColumn, UpdatedBy)))
success = true;
}
catch
{
success = false;
}
return success;
}
The code works as is, which by that I mean it saves the data back to the database. However CodeRush complains about the dt being an Unused Declaration. And since the Using is (I think) using the dt I would think that the warning is a false positive. So I am left wondering if CodeRush is wrong or if I am missing something?
回答1:
What CR is trying to say is that in:
using (DataTable dt = DataAccess.ExecuteDataTable ...
you are not using the declaration of dt
; the variable remains untouched after.
The refactor button will transform this to
using ( DataAccess.ExecuteDataTable ...
i.e. it will still be a using
statement but you won't have a variable to refer to it.
While you're doing that, you can do some Inline Result transformations, yielding:
try
{
using (DataAccess.ExecuteDataTable("[dbo].[udp_Customers_ups]",
DataAccess.Parameter(CustomerIdColumn, CustomerId),
DataAccess.Parameter(CodeColumn, Code),
DataAccess.Parameter(CompanyColumn, Company),
DataAccess.Parameter(IsDeletedColumn, IsDeleted),
DataAccess.Parameter(LastUpdatedColumn, LastUpdated),
DataAccess.Parameter(UpdatedByColumn, UpdatedBy)))
return true;
}
catch
{
return false;
}
I'll let others question whether wrapping calls like this in a catch
block is a good idea...
来源:https://stackoverflow.com/questions/29448120/why-does-coderush-warn-me-of-an-unused-declaration-in-code