C# : 'is' keyword and checking for Not

后端 未结 12 2029
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 05:23

This is a silly question, but you can use this code to check if something is a particular type...

if (child is IContainer) { //....

Is ther

12条回答
  •  感动是毒
    2020-12-02 06:14

    While this doesn't avoid the problem of parentheses, for the sake of people getting here via Google, it should be mentioned that newer syntax exists (as of C# 7) to make the rest of your code a little cleaner:

    if (!(DocumentPart is IContainer container)) { return; }
    foreach(DocumentPart child in container.Children) {
        ...
    

    This avoids the double-cast, the null-check, and having a variable available in scopes where it could be null.

提交回复
热议问题