C# : 'is' keyword and checking for Not

后端 未结 12 1989
没有蜡笔的小新
没有蜡笔的小新 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:04

    This hasn't been mentioned yet. It works and I think it looks better than using !(child is IContainer)

    if (part is IContainer is false)
    {
        return;
    }
    

    New In C# 9.0

    https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#logical-patterns

    if (part is not IContainer)
    {
        return;
    }
    
    0 讨论(0)
  • 2020-12-02 06:04

    Ugly? I disagree. The only other way (I personally think this is "uglier"):

    var obj = child as IContainer;
    if(obj == null)
    {
       //child "aint" IContainer
    }
    
    0 讨论(0)
  • 2020-12-02 06:05
    if (child is IContainer ? false : true)
    
    0 讨论(0)
  • 2020-12-02 06:08

    The is operator evaluates to a boolean result, so you can do anything you would otherwise be able to do on a bool. To negate it use the ! operator. Why would you want to have a different operator just for this?

    0 讨论(0)
  • 2020-12-02 06:13

    While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.

    MyClass mc = foo as MyClass;
    if ( mc == null ) { }
    else {}
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题