Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c# - Is there a way that I could assign a value to a variable at the same time as checking if it's null or not?

I currently have this code:

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

Is here a way that I could assign (bindable as SingleEntryGrid) to a variable while at the same time checking it is not null and then use that for the next line such that the next line became:

    singleEntryGrid._column3.Width = (double)newValue;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suppose you could use ??= to supply a new object if the existing is null:

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

Replace ColumnThing with the type _column3 has. You can set more properties with { X = Y } initializer after the ()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...