C# : 'is' keyword and checking for Not

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

    The way you have it is fine but you could create a set of extension methods to make "a more elegant way to check for the 'NOT' instance."

    public static bool Is(this object myObject)
    {
        return (myObject is T);
    }
    
    public static bool IsNot(this object myObject)
    {
        return !(myObject is T);
    }
    

    Then you could write:

    if (child.IsNot())
    {
        // child is not an IContainer
    }
    

提交回复
热议问题