有类似的问题,但回答并不是我要找的。如果引用为NULL或尚未分配值,我想将NULL值插入SQL Server数据库。目前我正在测试null并且看起来......(无法翻译完整,因为上下文不够清晰)
String testString = null;
if (testString == null)
{
command.Parameters.AddParameter(new SqlParameter("@column", DBNull.Value);
}
else
{
command.Parameters.AddParameter(new SqlParameter("@column", testString);
}
这对我来说看起来感觉非常笨拙。我有很多要插入到数据库中的值,像上面那样测试它们很冗长。.Net没有以某种方式处理这个吗?我以为如果我使用字符串而不是String可能会有用,但似乎也不起作用。我在四处寻找发现了一些关于使用Nullable类型的文章。
System.Nullable<T> variable
这似乎对原始类型、int?、char?double?和bool?都有效。所以这对那些可能有效,但是字符串呢?我有遗漏什么吗?我应该使用哪种类型来代替原始值和字符串值,以便在插入它们之前不需要重复测试值。
EDIT: Before I get too many answers about ternary operators. I like them but not in this context. It doesn t make sense for me to need to test that value and have all that extra logic, when that sort of thing could have been inplemented lower down in the .Net framework and if I knew what types to give then it would get it for free.
Edit: Okay, so guys help me formulate my plan of attack. I will use the Nullable for my primitives (int?, double? etc) and for my Strings I will use the String but the ?? test. This keeps things less verbose. Is there anything that I am missing here, like maybe losing some semantics?