繁体   English   中英

如果在C#中Value不为null,则将“ Value”设置为对象“ Only”中的字段

[英]Setting a Value to a field inside an object “Only” if the Value is not null in C#

我是C#的新手。 我可以在下面使用您的帮助。 我有以下代码。

    private void foo(TropicalRequest tropicalRequest)
    {
    var buildRequest = new RestRequest()
     {
      BaseUrl = tropicalRequest.baseUrl,
      StatusCode = tropicalRequest.statusCode,
      InitialDate = tropicalRequest.createdDate.Value
     };
    //Code call to save into DB
    }

“ tropicalRequest.createdDate.Value”字段不包含每个方案的值,如果该字段为null,则代码中断。 我已经编写了以下代码,但是我想对其进行优化,非常感谢您的帮助。

    private void foo(TropicalRequest tropicalRequest)
    {
    var buildRequest = new RestRequest()
     {
      BaseUrl = tropicalRequest.baseUrl,
      StatusCode = tropicalRequest.statusCode
     };

    if(tropicalRequest.createdDate.HasValue)
      buildRequest.InitialDate = tropicalRequest.CreatedDate.Value;
    //Code call to save into DB
    }

基本上,我想仅在值不为null时才将值设置为对象内的字段。

编辑1:InitialDate和CreatedDate都是DataType DateTimeOffset。

编辑#2:InitialDate不能为空,而CreatedDate可以为null的DateTimeOffset。

您可以使用null传播运算符:

var buildRequest = new RestRequest()
 {
  BaseUrl = tropicalRequest.baseUrl,
  StatusCode = tropicalRequest.statusCode,
  InitialDate = tropicalRequest.createdDate ?? default(DateTimeOffset)
 };

重要说明,DateTime对象的Default值是其MinValue ,这意味着如果您未分配任何内容,则其值将为01/01/0001 00:00:00 在第二个示例中,考虑tropicalRequest.CreatedDatenull ,则buildRequest.InitialDate将是最小值。

如果您希望它为null意味着它应该为Nullable类型。 您可以使用以下语法来定义它们。

 DateTime? InitialDate; 

如果在类中这样声明,则无需检查HasValue属性。 您可以像这样直接分配InitialDate = tropicalRequest.createdDate

如其他答案所述,如果您使用的是c# 6.0 ,则可以尝试Null-conditional Operators运算符。 否则使用条件运算符:

var buildRequest = new RestRequest()
 {
  BaseUrl = tropicalRequest.baseUrl,
  StatusCode = tropicalRequest.statusCode,
  InitialDate = tropicalRequest.createdDate.HasValue ? tropicalRequest.CreatedDate.Value : DateTime.MinValue;
 };

编译器已经对其进行了优化。 如果只想以不同的方式设置代码格式,则可以使用此语法。 因此,如果有值,将使用CreatedDate,否则在??的另一侧提供该值。 语法,在这种情况下为default(DateTimeOffset),它将与未分配的相同。 因此,有人可能会说您当前的语法实际上比这更好。

private void foo(TropicalRequest tropicalRequest)
{
    var buildRequest = new RestRequest()
    {
        BaseUrl = tropicalRequest.baseUrl,
        StatusCode = tropicalRequest.statusCode,
        InitialDate = tropicalRequest.CreatedDate ?? default(DateTimeOffset);
    };
}

由于您的InitialDate非null,所以DateTimeOffset始终会初始化为DateTimeOffset的默认值,即使您未分配它也是如此。

暂无
暂无

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

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