More user-friendly Compile-time type checking / 更加人性化的编译时类型检查 #7779
Unanswered
gdr2333
asked this question in
Language Ideas
Replies: 2 comments 1 reply
-
Thanks for the report. This is a question about C# casting and semantics, so I'm going to transfer to the Roslyn repo. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Moving to csharplang as this is a request about target-typing conditional expresions.s |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Sorry, my English is poor. For the sake of communication with you, the following English is all machine-translated, which may be a bit weird. I'm going to attach the original Chinese text, if you know Chinese (or have a better translator), then you should check it out.
Feature Request: More user-friendly compile-time type checking.
Take a look at this code:
Looks perfectly normal - Bits will only be 64 or 32, and it shouldn't cause any problems.
But it seems that the compiler doesn't think so. If you try to compile this code, it produces CS0266 - "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)"
There are some more complicated cases, like this one:
Neither 114 nor 514 will exceed the upper limit of the short type, in fact, the aByte here can be any value, because there is a variable of type byte that must not exceed the limit of the short type.
But like the previous example, this code produces CS0266 - "Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)"
Describe the solution you'd like
These two pieces of code should not produce any compilation errors.
Strict compile-time type checking is a good thing, it prevents a lot of errors from happening, but it's obviously a bit overdone - the compiler is just guarding against errors that can never happen.
Additional context
In fact, we're already doing it.
and
These two pieces of code don't produce any errors or warnings, because you know it's safe — but byte Bits = Environment.Is64BitProcess ? 64 : 32; is just as safe, and there's no reason to treat them differently.
中文原文
功能请求:更加人性化的编译时类型检查。
看看这段代码:
看起来非常正常——Bits只会是64或者32,它不应该产生任何问题。
但似乎编译器并不是这么想的。如果尝试编译这段代码,它会产生CS0266——“无法将类型“int”隐式转换为“byte”。存在一个显式转换(是否缺少强制转换?)”
还有一些更复杂的情况,比如这个:
不管是114还是514都不会超出short类型的上限,实际上,这里的aByte可以是任何值,因为有一个byte类型的变量一定不会超出short类型的限制。
但与上一个例子一样,这段代码会产生CS0266——“无法将类型“int”隐式转换为“short”。存在一个显式转换(是否缺少强制转换?)”
Describe the solution you'd like
这两段代码不应该产生任何编译错误。
严格的编译时类型检查是好事,它可以阻止大量的错误发生,但这很明显有些过火了——编译器只是在防范一些永远不可能发生的错误。
Additional context
事实上,我们已经在这么做了。
和
这两段代码不会产生任何错误和警告,因为你们知道这是安全的——但是 byte Bits = Environment.Is64BitProcess ? 64 : 32; 也一样安全,没有理由对它们区别对待。
Beta Was this translation helpful? Give feedback.
All reactions