可C#编译器进行配置,以给予警告,当明确的转换可能导致数据丢失? [英] Can C# compiler be configured to give warning when explicit cast may cause data loss?

查看:177
本文介绍了可C#编译器进行配置,以给予警告,当明确的转换可能导致数据丢失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有配置VS2008 C#编译器发出警告对于这样的代码的方式:

 的Int64 X = 123456789000 ; 
的Int32 Y =(Int32)已X;


解决方案

显式类型转换的整点是说, 我拿的问题,请你只做到这一点的责任。



在你的琐碎情况下,或许会很容易让编译器计算出的值不会,适合在一个的Int32,进而产生你的警告



不过,关于这一点:

 的Int64 X = CallSomeMethod(); 
的Int32 Y =(Int32)已X;



如何可以在警告你这件事?应该是:




  1. 尝试找出从CallSomeMethod值可以返回什么样的范围

  2. 随时警告? (然后就点是什么呢?),你可以希望在这里



最好是有一个运行时检查,或类似的编译器不能阻止你的一切可能出错。


Is there a way to configure the VS2008 C# compiler to give a warning for code like this:

Int64 x = 123456789000;
Int32 y = (Int32)x;

解决方案

The whole point of an explicit cast is to say that "I take responsibility for the problem, please just do it."

In your trivial case, it would perhaps be easy for the compiler to figure out that the value would not fit in a Int32, and thus produce your warning.

However, what about this:

Int64 x = CallSomeMethod();
Int32 y = (Int32)x;

How can it warn you about this? Should it:

  1. try to figure out what kind of range the value from CallSomeMethod could return?
  2. always warn? (then what would the point be?)

The best you can hope for here is to have a runtime check, or similar, the compiler cannot prevent you from everything that could go wrong.

这篇关于可C#编译器进行配置,以给予警告,当明确的转换可能导致数据丢失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆