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

后端 未结 6 1983
囚心锁ツ
囚心锁ツ 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: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.

提交回复
热议问题