I have just finished converted a vb.net app to c# and one of the lines is to get @ReturnValue from the parameter.
I ended up having to CAST a lot of things..
Is there not a easier way
here is what i have
int rc = ((System.Data.SqlTypes.SqlInt32)(((System.Data.SqlClient.SqlParameter)(cmd.Parameters["@ReturnValue"])).SqlValue)).Value;
In vb.net it was as simple as doing this
Dim rc As Integer = Convert.ToInt32(cmd.Parameters("@ReturnValue").Value)
Alot easier :-)
But the problem with C# is the property Value isn't available unless I Cast to SqlParameter and i also need to cast to Sqltypes.SqlInt32 - i can't just do a standard Convert.开发者_如何学CToInt32
This isn't a C# versus VB.NET thing - it's about the types you're using to declare your variables. If cmd
is an IDbCommand
, you're in for a lot of casting.
The IDbCommand.Parameters
property returns an IDataParametersCollection
, which contains a collection of Object instances. Since Object doesn't have a property called Value
, you need to cast each instance to SqlParameter
before accessing Value.
SqlCommand.Parameters
, by contrast is a SqlParameterCollection
, which contains a collection of SqlParameter
instances. If you declare your cmd
variable as a SqlCommand
, you can access its parameters' values in the straightforward way to which you're accustomed. (At the cost of being tightly coupled to the implementations in the SqlClient namespace.)
It's just as easy to do it in C#:
int rc = (int) cmd.Parameters("@ReturnValue").Value;
精彩评论