简体   繁体   English

SqlParameter构造函数与对象初始值设定项的问题

[英]Issues with SqlParameter constructor vs object initializer

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. 我收到以下错误:SqlParameterCollection只接受非null的SqlParameter类型对象,而不是String对象。

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? 关于为什么会发生这种情况的任何指针?

The problem is a misplaced closing parenthesis: 问题是错误的右括号:

cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar)).Value = customer.DisplayId;

Note that there are 2 closing parentheses before .Value . 请注意, .Value之前有两个右括号。 As you originally entered it, you are doing cmd.Parameters.Add(...); 正如您最初输入的那样,您正在做cmd.Parameters.Add(...); where the ... is ...的地方

new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayId

and that evaluates to customer.DisplayId , hence the message about it not accepting string types. 并且评估为customer.DisplayId ,因此关于它的消息不接受string类型。

Also, you can add the parameter more succinctly with 此外,您可以更简洁地添加参数

cmd.Parameters.AddWithValue("@displayId", customer.DisplayId);

As to why new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayId returns customer.DisplayId , consider that the assignment operator returns the value being assigned as its result, and in this case that would be customer.DisplayId . 至于为什么new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayId返回customer.DisplayId ,请考虑赋值运算符返回被指定为其结果的值,在这种情况下将是customer.DisplayId This is why you can assign a value to several variables at once: 这就是您可以一次为多个变量赋值的原因:

int i, j, k;
i = j = k = 42;
cmd.Parameters.Add(new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customer.DisplayID);

is the same as 是相同的

var customerDisplayId = customer.DisplayID;
new SqlParameter("@displayId", SqlDbType.NVarChar).Value = customerDisplayId;
cmd.Parameters.Add(customerDisplayId);

now do you see why the compiler is complaining? 现在你明白为什么编译器会抱怨吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM