【问题标题】:Converting a string to a nullable int [duplicate]将字符串转换为可为空的 int [重复]
【发布时间】:2014-05-25 13:42:53
【问题描述】:

如果_model.SubBrand 是一个字符串,有没有更优雅的方式将其转换为可为空的int?我现在正在做的事情感觉很笨拙:

public int? SubBrandIndex
{
    get
    {
        return _model.SubBrand == null ?
            (int?)null : Convert.ToInt32(_model.SubBrand);
    }
}

【问题讨论】:

标签: c# int type-conversion nullable boxing


【解决方案1】:

为什么要单行,在我看来这是非常清晰易读的:

public int? SubBrandIndex
{
    get
    {
        int? subBrandIndex = null;
        if (_model.SubBrand != null)
            subBrandIndex = int.Parse(_model.SubBrand);
        return subBrandIndex;
    }
}

【讨论】:

    【解决方案2】:

    为了避免异常,还应该检查无效字符串

    public int? SubBrandIndex
    {
        get
        {
            int value;
            return int.TryParse(subBrand, out value) ? (int?)value : null;
        }
    }
    

    【讨论】:

    • 可能_model.SubBrand 不是用户分配的,如果无法解析非空字符串,则应将其视为异常,因为这是一个错误。如果返回 nullable-int,则无法区分 null 字符串和无效的非 null 字符串。
    猜你喜欢
    • 2015-06-18
    • 2017-05-07
    • 1970-01-01
    • 2014-03-02
    • 2012-01-24
    • 2013-11-04
    • 2021-12-25
    • 2016-07-07
    • 1970-01-01
    相关资源
    最近更新 更多