首页 > 解决方案 > 有没有一种方法可以在检查变量是否为空的同时为变量赋值?

问题描述

我目前有这个代码:

    private static void IsEntryWidthChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if ((bindable as SingleEntryGrid)._column3 != null)
            (bindable as SingleEntryGrid)._column3.Width = (double)newValue;
    }

这是一种我可以将(可绑定为 SingleEntryGrid)分配给变量的方法,同时检查它是否为空,然后将其用于下一行,以便下一行变为:

    singleEntryGrid._column3.Width = (double)newValue;

标签: c#

解决方案


如果现有对象为空,我想您可以使用它??=来提供新对象:

((bindable as SingleEntryGrid)._column3 ??= new ColumnThing()).Width = newValue;

替换ColumnThing为具有的类型_column3{ X = Y }您可以在初始化器之后设置更多属性()


推荐阅读