简体   繁体   English

在 c# 中将可空字符串转换为可空 int

[英]Convert nullable string to nullable int in c#

I have variable with below我有下面的变量

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

I need to assign a=b;我需要分配 a=b;

What is best way to assign in c# 9在 c# 9 中分配的最佳方法是什么

a= Convert.ToInt32(b);

It is assigning 0..hw to assign null if string also null.. i need to know in c# 9如果字符串也是 null.. 我需要知道 c# 9

EDIT: Thanks to @john.. i ended up with below code编辑:感谢@john ..我最终得到以下代码

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

I would just be very explicit about it:我会非常明确地说明这一点:

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

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

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