Parameters.Add(string, object) 和 Parameters.AddWithValue 之间的区别 [英] Difference between Parameters.Add(string, object) and Parameters.AddWithValue

查看:14
本文介绍了Parameters.Add(string, object) 和 Parameters.AddWithValue 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了 MSDN 文档和示例 here 并且我知道 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆