C# : 'is' keyword and checking for Not

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

    The extension method IsNot is a nice way to extend the syntax. Keep in mind

    var container = child as IContainer;
    if(container != null)
    {
      // do something w/ contianer
    }
    

    performs better than doing something like

    if(child is IContainer)
    {
      var container = child as IContainer;
      // do something w/ container
    }
    

    In your case, it doesn't matter as you are returning from the method. In other words, be careful to not do both the check for type and then the type conversion immediately after.

提交回复
热议问题