简体   繁体   English

分配前检查value是否为null

[英]Checking if value is null before assigning

so I am creating a new object and setting its properties from other functions. 所以我要创建一个新对象,并通过其他功能设置其属性。 I need to check if those are null before applying the values. 在应用这些值之前,我需要检查那些是否为空。 How would I approach this? 我将如何处理?

Customer = new Customer (
     name = requestCall.Name, 
     age = requestCall.Age.ofType<DateTime>().DOB
    )

how would I check if requestCall.Age or requestCall.Name is not null before applying? 在申请之前,如何检查requestCall.Age或requestCall.Name是否不为null?

Depending on your scenario you can use ternary operator 根据您的情况,您可以使用三元运算符

name = requestCall.Name == null ? something : something_else

or null coalesce operator null合并运算符

name = requestCall.Name ?? something

Variant 1: 变体1:

Customer = new Customer(
     name = requestCall.Name ?? "default name", 
     age = requestCall.Age == null ? (some default date) :  requestCall.Age.ofType<DateTime>().DOB
);

Variant 2: 变体2:

Customer = requestCall == null ? null : new Customer(
     name = requestCall.Name, 
     age = requestCall.Age.ofType<DateTime>().DOB
);

Of course, you can use if and to my mind, it is better: 当然,您可以使用if和我认为更好的方法:

Customer customer;
if (requestCall != null)
{
    customer = new Customer();
    if (requestCall.Name != null)
    {
        customer.Name = requestCall.Name;
    }
    // etc.
}
else
{
    customer = null;
}

Just make a requestCall.IsValid() method (aptly named something that fits in with your usage) and use this to verify whether or not you are able to make a new customer. 只需创建一个requestCall.IsValid()方法(恰当地命名为适合您用法的名称)并使用它来验证您是否能够结交新客户。

I'd imagine the logic will grow as you determine other things that need to be added and this will reduce the amount of updating you'll have to do. 我以为逻辑会随着您确定需要添加的其他内容而增长,并且这将减少您必须执行的更新量。

As a side note to this: You may wish to make a constructor that takes in a requestCall as a parameter. 附带说明一下:您可能希望创建一个将requestCall作为参数的构造函数。

try this 尝试这个

Customer = new Customer (
     name = requestCall.Name ?? string.Empty, 
     age = requestCall.Age.ofType<DateTime>().DOB ?? DateTime.Now
    )

Do it as 照做

 requestCall.Name ?? "soome text", 

or !string.IsNullOrEmpty(requestCall.Name) ? requestCall.Name : "soome text" !string.IsNullOrEmpty(requestCall.Name) ? requestCall.Name : "soome text" !string.IsNullOrEmpty(requestCall.Name) ? requestCall.Name : "soome text" , !string.IsNullOrEmpty(requestCall.Name) ? requestCall.Name : "soome text"

and check null for integer as 并检查null为整数

 `age = requestCall.Age == null ? (default) :  requestCall.Age.ofType<DateTime>().DOB`

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

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