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
相关产品推荐
相关产品推荐

