Why use TryCast instead of DirectCast?

后端 未结 4 478
粉色の甜心
粉色の甜心 2020-12-03 02:53

When I am trying to cast Object obj to Type T, if it can not be cast then there is something wrong.

And after I cast the object I will be l

4条回答
  •  醉梦人生
    2020-12-03 03:41

    If your design mandates that the object passed to you MUST be of type T, then assert (as in Debug.Assert) that the cast succeeds in debug builds and run exhaustive unit tests to prove that your implementation follows your design.

    With your design proven and tested, you can perfrom the direct cast knowing that it can never fail.

提交回复
热议问题