在将值分配给属性之前,将空字符串/空值替换为0 [英] Replacing empty string/null value with 0 prior to assigning value to a property

查看:207
本文介绍了在将值分配给属性之前,将空字符串/空值替换为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让以下代码分配一个在app.config和Cache中定义的值,该值在缓存中作为公共枚举类"检索,如下所示:

Got the following code to assign a value which is defined in the app.config and Cache, this value is retrieved in cache as "public enum class" such as in the following:

public static class Cache
{
  public enum jobDetails { x }; 
}



这是在app.config中定义的变量:



Here is the variable defined in app.config:

<add key="x" value=""/>



并且objectDetails定义如下:



and the objectDetails is defined as in the following:

public class objectDetails
{ 
   public int x { get; set; }
}



这是我遇到麻烦的一段代码:



Here is the piece of code that I am having trouble with:

objectDetails.x = Convert.ToInt16(jobDetails.GetValues(Cache.jobDetails.x.ToString().Trim())[0]);



我的问题是,如果在app.config文件中将"x"定义为空值("),则上述代码将失败(由于字符串格式错误),因此,如果它是null值("),然后将其分配为0,然后再将该值分配给objectDetails.x(并优雅地执行此操作).



My question is here is if "x" is defined as null value ("") in the app.config file then the above code would fail (due to string format error), so how can I check the value upfront if it is a null value ("") then assign a 0 to it before assigning the value to objectDetails.x (and do that elegantly).

推荐答案

您收到的错误是因为如果无法将参数解析为16位整数,则Convert.ToInt16会引发异常,因此必须确保如果对Convert.ToInt16进行调用,则您提供的参数是有效的.

在您的情况下,Cache.jobDetails.X.ToString()中的问题为空或为空,因此string.IsNullOrEmpty(Cache.jobDetails.x.ToString())是您需要检查的问题.

例如.
The error you are receiving is because Convert.ToInt16 will throw an exception if the argument cannot be parsed into a 16bit integer, so you have to ensure that if you make a call to Convert.ToInt16 the argument you supply it is valid.

In your case the problem in Cache.jobDetails.X.ToString() being empty or null, so string.IsNullOrEmpty(Cache.jobDetails.x.ToString()) is what you need to check.

eg.
objectDetails.x = 
   string.IsNullOrEmpty(Cache.jobDetails.x.ToString().Trim()) 
      ? 0 
      : Convert.ToInt16(jobDetails.GetValues(Cache.jobDetails.x.ToString().Trim())[0]);


if (jobDetails.X.HasValue)
...{ assign to objectDetails}


这篇关于在将值分配给属性之前,将空字符串/空值替换为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆