c# - 处理新 linq 对象中的空返回 c#
问题描述
我要去做什么?我需要将一个新创建的对象发布到数据库,传入的对象可能有一个空值。创建的对象设置#nullible true
在需要的地方。
当数据进入并且我落在我的对象中的一个空字符串上时,我得到一个空引用并抓住了。
我的代码:
Objects.Data.Info.StoredData postData = new Objects.Data.Info.StoredData
{
Name = data.data.Name,
Type = data.data.Type,
Price = data.data.Price,
Indicator = data.data.Indicator,
Scan = data.data.Scan,
Comment = data.data.Extra
};
db.Information.Add(postData);
db.SaveChanges();
data.data.Extra 有时可以为空。
我通常会写 if 语句来解决这个问题,但不觉得这是最好的做法。我应该往哪个方向走?我检查了其他一些问题和 msdn,但找不到明确的路径。
谢谢。
解决方案
当属性为 null 时,您可以使用运算符简洁地默认为空字符串??
,如下所示:
Comment = data.data.Extra ?? ""
//the value on the right is used if the expression on the left is null
??
被称为“null-coalescing”运算符:https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator
如果您还想处理为 null 的中间属性(我认为这不适用于这种情况,但很高兴知道),并且仍想默认为空字符串,您可以将其与 Eugene 的使用?.
like so的建议结合起来:
Comment = data?.data?.Extra ?? ""
推荐阅读
- azure - 写入 Azure Cosmos , 吞吐量 RU
- c# - Automapper:无法为集合创建抽象类型的实例
- reactjs - 用redux中的dispatch()和connect()解释这个问题?
- flutter - 何时使用 Provider.of
与消费者 在颤振中 - javascript - 有没有办法在 JavaScript 中生成一个随机数,然后用它来生成另一个随机数?
- ruby-on-rails - Ruby GraphQL 返回不同的类型
- ecmascript-6 - 在 ECMAScript 规范中的什么地方指定了等待表达式的返回值?
- laravel - 在 Laravel 中使用 isDirty
- macos - 来自 `SFSpeechRecognizer` `recognitionTask` 在约 30 秒标记处的不需要的回调
- reactjs - React - 在 PRODUCTION 构建中获取“.map 不是函数”,但在常规开发构建中没有?