我有一个asp.net文本表单,其中包含许多可选的小数字段。我想有选择地更新数据库,但不为没有数据的字段插入"0“(保持null状态)。
通常,我会创建多个函数,每个函数都有不同的签名来处理这个问题。但是,我通过does服务插入数据,该does服务不允许具有相同名称的函数具有多个签名。我可以想出几种方法来解决这个问题,但没有一种是“实用的”。
发布于 2008-10-07 20:10:54
Nullable Types的目的是相同的。它们表示值类型,其中可能没有数据。可以使用这些类型的HasValue属性检查值的存在。
读取字段的伪代码:
decimal? dValue; // default value is null
if(decimalValueExists)
{
dValue = <value read from text file>
}
当你说多个方法时-我假设这些都是重载的方法,以便能够添加可选字段(所以n个可选字段意味着更多n个方法)
您可以通过编写单个方法来避免编写这些方法。假设您有一个必填字段和一个可选字段:
public class MyFields
{
decimal req1;
decimal? opt1; // optional field 1
}
然后定义使用它的web服务方法:
[WebMethod]
void MyWSMethod(MyFields myFields)
{/* code here will ultimately call InsertMyFields */}
void InsertMyFields(MyFields myFields)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "AddMyFields";
command.CommandType = CommandType.StoredProcedure;
// Add the required input parameter
SqlParameter parameter1 = new SqlParameter();
parameter1.ParameterName = "@ReqField1";
parameter1.SqlDbType = SqlDbType.NVarChar;
parameter1.Direction = ParameterDirection.Input;
parameter1.Value = myFields.req1;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter1);
// Add the optional parameter and set its properties.
SqlParameter parameter2 = new SqlParameter();
parameter2.ParameterName = "@OptField1";
parameter2.SqlDbType = SqlDbType.NVarChar;
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = myFields.opt1 ?? DBNull.Value; //null coalescing operator
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter2);
//.. rest of the code
}
}
如果可为空的类型有一个值,Null Coalescing Operator将设置该值,否则它将设置您指定的另一个值(在本例中为DBNull.Value)。
发布于 2008-10-07 20:23:19
您可以将参数定义为可以为空的小数。可为空值类型的C#语法如下:
decimal? rebateAmountOrWhatever;
然后,您可以将空值存储在变量中,并将变量与空值进行比较。
new SqlParameter("@RebateAmount",
rebateAmountOrWhatever == null ? (object)DBNull.Value : (object)rebateAmountOrWhatever)
使用??也有很大的乐趣。像这样的运算符:
new SqlParameter("@RebateAmount",
(object)rebateAmountOrWhatever ?? (object)DBNull.Value)
声明变量的另一种等效方法是使用Nullable<>泛型类型,如下所示:
Nullable<decimal> currentIraBalance = null;
发布于 2008-10-07 19:27:49
您可以在web服务代码中使用DBNull class来表示空值。
而您仍然必须使用代理值(例如,0或-1),然后只需计算该值以将其转换为DBNull
对象。
https://stackoverflow.com/questions/181210
复制相似问题