首页 > 解决方案 > 在c#中将可空字符串转换为可空int

问题描述

我有下面的变量

  int? a=null ;
    
  string? b= null;

我需要分配 a=b ;

在 c# 9 中分配的最佳方法是什么

a= Convert.ToInt32(b);

它分配 0 ..hw 来分配 null 如果字符串也为 null .. 我需要在 c# 9 中知道

编辑:感谢@john ..我最终得到以下代码

  if(b is not null) 
     a = Convert.ToInt32(b); 

标签: c#c#-9.0

解决方案


我会非常明确地说明这一点:

int? a = b is null ? null : Convert.ToInt32(b);

推荐阅读