简体   繁体   English

DBNull.Value作为可选参数

[英]DBNull.Value as optional parameter

Is is possible to pass DBNull.Value as optional parameter? 可以将DBNull.Value作为可选参数传递吗? I tried in C# 我试过C#

private void CallSP(string param0, string param2 = DBNull.Value)
{
}

Its is giving error. 它给出了错误。 I need to call a Stored procedure in this method, so i am passing DBNull.Value. 我需要在这个方法中调用一个Stored过程,所以我传递了DBNull.Value。 Is'DBNull.Value' and 'null' are treated as same in SQL Server? 在SQL Server中,'DBNull.Value'和'null'被视为相同吗? Shall i pass 'null' instead of 'DBNull.Value'??? 我应该传递'null'而不是'DBNull.Value'???

DBNull.Value is not a string, and is not a constant (optional parameter values must be constants). DBNull.Value 不是字符串,并且不是常量(可选参数值必须是常量)。 The way to do this is to default it to regular null , and handle the null when adding the parameter: 执行此操作的方法是将其默认为常规null ,并在添加参数时处理null

private void CallSP(string param0, string param2 = null)
{
    ...
    object value = (object)param2 ?? DBNull.Value;
    // ^^^ use value in the parameter
    ...
}

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

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