Is there more to the C# “as” keyword than simple casting?

后端 未结 6 1985
囚心锁ツ
囚心锁ツ 2021-02-05 22:26

I\'m working through Josh Smith\'s CommandSink code obviously do not understand something about the \"as\" keyword in C#.

I don\'t understand why he wrote the line:

相关标签:
6条回答
  • 2021-02-05 22:41

    as does "cast, if it is", and equivalent to:

    (X is TYPE) ? (TYPE) X : null

    it is however, more efficient than is + cast.

    depObj may implement either interface, none, or both.

    0 讨论(0)
  • 2021-02-05 22:48

    as will return an object of the type you requested, if the operand is compatible. If it isn't, it will return null. If you use as and it is possible that the cast will fail, you need to check to make sure the reference is valid.

    For example, if depObj was of type String, it would not be null, but it would also not be able to be converted to either of the requested types and both of those variables would become null.

    0 讨论(0)
  • 2021-02-05 22:49

    First, the as keyword includes a is check.

    if( o is A)
       a = (A) o;
    

    is the same as

    a = o as A;
    

    Second, as does not convert the Type like a cast does, even if a conversion operator from Type A to B is defined.

    0 讨论(0)
  • 2021-02-05 22:57

    What if depObj is neither a FrameworkElement or a FrameworkContentElement? I don't know the full scenario (i.e. what the types are likely to be), but this seems a reasonable defensive strategy.

    0 讨论(0)
  • 2021-02-05 22:57

    What if the DependencyObject depObj was actually a FrameworkOtherTypeOfElement

    Then depObj would not be null

    but the attempted as Casts would both evaluate to null and _fe & _fce would both be null

    as is equivalent to doing

    if(I Can Cast This Object)
       //Then cast it
    else
       //Return null
    
    0 讨论(0)
  • 2021-02-05 23:03
    IsValid = _fe != null || _fce != null;
    

    and

    IsValid = depObj != null;
    

    are not the same tests because if depObj is not of type FrameworkElement nor FrameworkContentElement but is not null the second test will return true, while the first will return false.

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