You need to enable JavaScript to run this app. C#中能否在类型转换判空的同时为变量赋值,简化冗余代码?
优惠活动
大模型
产品
解决方案
定价
更多

C#中能否在类型转换判空的同时为变量赋值,简化冗余代码?

实现方案

现代C#(C# 7.0及以上,推荐)

用模式匹配is表达式,一步完成类型转换、变量赋值、非空校验,无重复转换代码:
C# 9.0及以上写法:

private static void IsEntryWidthChanged(BindableObject bindable, object oldValue, object newValue)
{
    if (bindable is not SingleEntryGrid singleEntryGrid || singleEntryGrid._column3 == null)
        return;

    singleEntryGrid._column3.Width = (double)newValue;
}

C# 7.0 ~ 8.x 兼容写法(不支持is not语法):

private static void IsEntryWidthChanged(BindableObject bindable, object oldValue, object newValue)
{
    if (!(bindable is SingleEntryGrid singleEntryGrid) || singleEntryGrid._column3 == null)
        return;

    singleEntryGrid._column3.Width = (double)newValue;
}

低版本C#(C# 7.0以下)

用as做安全转换后统一判空:

private static void IsEntryWidthChanged(BindableObject bindable, object oldValue, object newValue)
{
    SingleEntryGrid singleEntryGrid = bindable as SingleEntryGrid;
    if (singleEntryGrid == null || singleEntryGrid._column3 == null)
        return;

    singleEntryGrid._column3.Width = (double)newValue;
}

注意:原代码存在空引用隐患——如果传入的bindable无法转换为SingleEntryGrid,as返回null后直接访问_column3会抛出异常,上述实现均已修复该问题。

内容的提问来源于stack exchange,提问作者Rupert Bear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.09 13:24:05