SqlParameter 构造函数与对象初始值设定项的问题
给出以下代码行:
cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayID);
我收到以下错误: SqlParameterCollection 仅接受非空 SqlParameter 类型对象,而不接受 String 对象。
但是,重写它以使用对象初始化:
cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar) { Value = customer.DisplayID });
效果很好。有任何关于为什么会发生这种情况的指示吗?
Given the following line of code:
cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayID);
I receive the following error:
The SqlParameterCollection only accepts non-null SqlParameter type objects, not String objects.
However, rewriting it to use object intialization:
cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar) { Value = customer.DisplayID });
works just fine. Any pointer on why this is occuring?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是右括号放错了位置:
请注意,
.Value
之前有 2 个右括号。正如您最初输入的那样,您正在执行cmd.Parameters.Add(...);
,其中...
是new SqlParameter("@displayId" ,SqlDbType.NVarChar).Value = customer.DisplayId
并且计算结果为
customer.DisplayId
,因此有关它的消息不接受string
类型。更简洁地添加参数
此外,您还可以使用As to Why
new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayId
returnscustomer.DisplayId
,考虑赋值运算符返回作为结果分配的值,在本例中为customer.DisplayId
。这就是为什么您可以一次为多个变量赋值:The problem is a misplaced closing parenthesis:
Note that there are 2 closing parentheses before
.Value
. As you originally entered it, you are doingcmd.Parameters.Add(...);
where the...
isnew SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayId
and that evaluates to
customer.DisplayId
, hence the message about it not acceptingstring
types.Also, you can add the parameter more succinctly with
As to why
new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayId
returnscustomer.DisplayId
, consider that the assignment operator returns the value being assigned as its result, and in this case that would becustomer.DisplayId
. This is why you can assign a value to several variables at once:和现在一样
你明白为什么编译器会抱怨吗?
is the same as
now do you see why the compiler is complaining?