Parameters.Add(string,object)和Parameters.AddWithValue之间的区别 [英] Difference between Parameters.Add(string, object) and Parameters.AddWithValue
问题描述
我在此处阅读MSDN文档和示例并且我知道Paramters.Add
调用的正确语法是:
I read the MSDN documentation and examples here and I know that the correct syntax for a Paramters.Add
call is :
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
必须在其中指定参数名称,SqlDbType
和使用.Value
的值.
Where you have to specify the Parameter Name, the SqlDbType
AND the Value with .Value
.
现在Parameters.AddWithValue
调用的正确语法是:
Now the correct syntax for a Parameters.AddWithValue
call is :
command.Parameters.AddWithValue("@demographics", demoXml);
单行并跳过Type
部分.
我的问题是:当我这样做时,
My Question is : How is it that when I do it like this,
command.Parameters.Add("@demographics", demoXml);
// .Add method with .AddWithValue syntax
我没有得到任何编译错误,甚至没有怪异的东西,在执行代码后,一切似乎都能正常工作?
I don't get any compiling error and even weirder, everything seems to work properly when the code is executed ?
推荐答案
功能上没有区别.实际上,两者都是这样做的:
There is no difference in terms of functionality. In fact, both do this:
return this.Add(new SqlParameter(parameterName, value));
之所以弃用旧版本而支持AddWithValue
的原因是为了增加清晰度,以及第二个参数是object
,这使得对于某些人来说,Add
的重载是立即不明显的.被称为,它们导致了截然不同的行为.
The reason they deprecated the old one in favor of AddWithValue
is to add additional clarity, as well as because the second parameter is object
, which makes it not immediately obvious to some people which overload of Add
was being called, and they resulted in wildly different behavior.
看看这个例子:
SqlCommand command = new SqlCommand();
command.Parameters.Add("@name", 0);
乍一看,它看起来像是在调用Add(string name, object value)
重载,但不是.它正在调用Add(string name, SqlDbType type)
重载!这是因为0可以隐式转换为枚举类型.所以这两行:
At first glance, it looks like it is calling the Add(string name, object value)
overload, but it isn't. It's calling the Add(string name, SqlDbType type)
overload! This is because 0 is implicitly convertible to enum types. So these two lines:
command.Parameters.Add("@name", 0);
和
command.Parameters.Add("@name", 1);
实际上导致两种不同的方法被调用. 1
不能隐式转换为枚举,因此它选择object
重载.使用0
,它将选择枚举重载.
Actually result in two different methods being called. 1
is not convertible to an enum implicitly, so it chooses the object
overload. With 0
, it chooses the enum overload.
这篇关于Parameters.Add(string,object)和Parameters.AddWithValue之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!