Is there a way to disable implicit casts from UInt32 to char?

后端 未结 4 1732
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 03:03

I am working on code that takes as input a ton of ascii text defined by specific protocol. The original author interpreted \"string(1)\" datatypes in the original protocol

4条回答
  •  猫巷女王i
    2021-01-18 03:53

    No, the behavior allowing the expression theChar == 7 is part of the C# specification, and can't be changed.

    Note that the actual implicit conversion here is from char to int, not from int to char.

    Here's how it works:

    • The literal 7 has type int.
    • The variable theChar has type char.
    • To apply the == operator to the two expressions, the compiler must choose an == operator.
      • There is no == operator that takes a char as the first argument and an int as the second.
      • There is no implicit conversion from int to char (because such a conversion can lose information).
      • There is an implicit conversion from char to int.
      • The compiler converts the char expression to int, and uses the == operator that takes two ints.

提交回复
热议问题