簡體   English   中英

如何在字符串插值 C# 中保留 null 值

[英]How to preserve null values in string interpolation C#

我想保留 null 值(將它們插入 DB),同時我將它們作為字符串傳遞給 C# 代碼中的 sql 變量。

var valString = new StringBuilder();
//somevalue is null at this point
valString.Append($"({id}, " +$"'{SomeValue}')");

字符串插值返回 SomeValue => '' 的空字符串,而不是 null。 我想在字符串插值中保留 null 並將其傳遞給查詢字符串。 可能嗎?

如果不是 null,這將使用 SomeValue,如果是,則使用 NULL。

var valString = new StringBuilder();
//somevalue is null at this point
valString.Append($"({id}," + (SomeValue == null ? "NULL" : $"'{SomeValue}'"));

你可以這樣做:

var valString = new StringBuilder();
valString.Append($"({id}, " +$"'{SomeValue ?? "null"}')");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM