<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>.NET编程 | 酷 壳 - CoolShell</title>
	<atom:link href="https://coolshell.cn/category/proglanguage/dotnet/feed" rel="self" type="application/rss+xml" />
	<link>https://coolshell.cn</link>
	<description>享受编程和技术所带来的快乐 - Coding Your Ambition</description>
	<lastBuildDate>Mon, 17 Mar 2014 00:56:54 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.2</generator>
	<item>
		<title>一个浮点数跨平台产生的问题</title>
		<link>https://coolshell.cn/articles/11235.html</link>
					<comments>https://coolshell.cn/articles/11235.html#comments</comments>
		
		<dc:creator><![CDATA[tanglei.name]]></dc:creator>
		<pubDate>Sat, 15 Mar 2014 12:44:24 +0000</pubDate>
				<category><![CDATA[.NET编程]]></category>
		<category><![CDATA[C/C++语言]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[float]]></category>
		<category><![CDATA[FPU]]></category>
		<category><![CDATA[SSE]]></category>
		<guid isPermaLink="false">http://coolshell.cn/?p=11235</guid>

					<description><![CDATA[<p>感谢网友唐磊（微博@唐磊_name）投稿，本文原文在唐磊的博客上（原文地址），原文分析还不够好，而且可能对人有误导，所以，我对原文做了很多修改，并加了Linux...</p>
<p class="read-more"><a class="btn btn-default" href="https://coolshell.cn/articles/11235.html"> Read More<span class="screen-reader-text">  Read More</span></a></p>
The post <a href="https://coolshell.cn/articles/11235.html">一个浮点数跨平台产生的问题</a> first appeared on <a href="https://coolshell.cn">酷 壳 - CoolShell</a>.]]></description>
										<content:encoded><![CDATA[<p><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3415450859608158"
     crossorigin="anonymous"></script><strong>感谢网友<a href="http://www.tanglei.name/" target="_blank">唐磊</a>（微博@<a title="唐磊_name" href="http://weibo.com/tangleithu?from=feed&amp;loc=nickname">唐磊_name</a>）投稿，本文原文在唐磊的博客上（<a href="http://www.tanglei.name/a-bug-relate-with-float-point-between-x86-and-x64-in-csharp/">原文地址</a>），原文分析还不够好，而且可能对人有误导，所以，我对原文做了很多修改，并加了Linux下的内容。浮点数是一个很复杂的事情，希望这篇文章有助于大家了解浮点数与其相关的C/C++的编译选项。</strong>（注：我没有Windows 32位以及C#的环境，所以，对于Windows 32位的程序和C#的程序没有验证过）</p>
<p>背景就简单点儿说，最近一个项目C#编写，涉及浮点运算，来龙去脉省去，直接看如下代码。</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">float p3x = 80838.0f;
float p2y = -2499.0f;
double v321 = p3x * p2y;
Console.WriteLine(v321);</pre>
<p>很简单吧，马上笔算下结果为-202014162，没问题，难道C#没有产生这样的结果？不可能吧，开启Visual Studio，copy代码试试，果然结果是-202014162。就这样完了么？显然没有！你把编译时的选项从AnyCPU改成x64试试~(服务器环境正是64位滴哦！！)结果居然边成了-202014160，对没错，就是-202014160。有点不相信，再跑两遍，仍然是-202014160。呃，想通了，因为浮点运算的误差，-202014160这个结果是合理的。</p>
<p>为什么合理呢？很正常，因为上面的p3x和p2y是两个float类型，虽然v321是double，但也是两个float类型计算完后再转成double的，<strong>float的精度本来也只有7位，所以，对于这个上亿的数，自然没有办法保证精度</strong>。</p>
<p><strong>但是为什么修改CPU的type会有不同的效果？</strong>嗯，我们再试试C/C++。</p>
<p><span id="more-11235"></span></p>
<pre data-enlighter-language="c" class="EnlighterJSRAW">#include
using namespace std;

int main()
{
    float p3x = 80838.0f;
    float p2y = -2499.0f;
    double v321 = p3x * p2y;
    std::cout.precision(15);
    std::cout &lt;&lt; v321 &lt;&lt; std::endl;

    return 0;
}
</pre>
<p>上面这段C++代码在不同的平台下的结果如下：</p>
<ul>
<li>Windows 32/64位下：-202014160</li>
<li>Linux 64位下（CentOS 6 gcc 4.4.7）-202014160，</li>
<li>Linux 32位下（Ubuntu 12.04+ gcc 4.6.3）是：-202014162</li>
</ul>
<p><strong>合理的结果应该是-202014160，正确的运算结果是-202014162</strong>，合理性是浮点精度不够造成的（文后解释了合理性）。若是用两个double相乘可得正确且合理的运算结果（注：把上面C++的程序中的p3x和p2y的类型声明成double，就能得到正确的结果，因为double是双精度的，float是单精度，所以double有足够的位数存放更多的数位）。<strong>但是我们有点不明白，为什么Linux 32位下，居然能算出“正确”的数，而不是“合理”的数</strong>。</p>
<p>与C++一样，C#在32位和64位（DEBUG下，这个后面会说）下没有得到一致的结果，那我们来看一下C++/C#的汇编代码（使用gdb的disassemble /m main 命令，另外下面只显示 float * float 然后转成double的那一行代码的汇编）</p>
<p><strong>Linux平台下用G++编译</strong></p>
<pre data-enlighter-language="c" class="EnlighterJSRAW">//C++ 32位系统下 Ubuntu 12.04
8	    double v321 = p3x * p2y;
   0x0804860f &lt;+27&gt;:	flds   0x18(%esp)
   0x08048613 &lt;+31&gt;:	fmuls  0x1c(%esp)
   0x08048617 &lt;+35&gt;:	fstpl  0x10(%esp)

.......</pre>
<pre data-enlighter-language="c" class="EnlighterJSRAW">//C++ 64位系统下 CentOS 6
9           double v321 = p3x * p2y;
   0x000000000040083c &lt;+24&gt;:    movss  -0x20(%rbp),%xmm0
   0x0000000000400841 &lt;+29&gt;:    mulss  -0x1c(%rbp),%xmm0
   0x0000000000400846 &lt;+34&gt;:    unpcklps %xmm0,%xmm0
   0x0000000000400849 &lt;+37&gt;:    cvtps2pd %xmm0,%xmm0
   0x000000000040084c &lt;+40&gt;:    movsd  %xmm0,-0x18(%rbp)</pre>
<p><strong>Windows平台下用Visual Studio编译</strong></p>
<pre data-enlighter-language="c" class="EnlighterJSRAW">//C# AnyCPU编译，Windows VS2012
double v321 = p3x * p2y;
00000049  fld         dword ptr [ebp-40h]
0000004c  fmul        dword ptr [ebp-44h]
0000004f  fstp        qword ptr [ebp-4Ch]</pre>
<pre data-enlighter-language="c" class="EnlighterJSRAW">//C# X64位编译 Windows7 VS2012
double v321 = p3x * p2y;&lt;/pre&gt;
009B43B8 movss xmm0,dword ptr [p3x]
009B43BD mulss xmm0,dword ptr [p2y]
009B43C2 cvtss2sd xmm0,xmm0
009B43C6 movsd mmword ptr [v321],xmm0</pre>
<p>从上面的汇编代码可以看出，无论是Linux和Windows，C++或C# 32位和64对浮点数的汇编指令并不一样。 32位生成代码用的指令是fld/fmul/fstp等，而64位下的使用了movss/mulss/movsd/的指令。看下来，似乎这个事情和平台有关系。</p>
<p>我们继续调查，我们发现，其中fld/fmul/fstp等指令是由<strong>FPU</strong>(float point unit)浮点运算处理器做的，准确的说，是FPU x87指令，FPU在进行浮点运算时，用了<strong>80位</strong>的寄存器做相关浮点运算，然后再根据是float/double截取成32位或64位，FPU默认上会尽量减少由于需要四舍五入带来的精度问题。可参看浮点运算标准<a href="http://en.wikipedia.org/wiki/IEEE_floating_point" target="_blank">IEEE-754</a> 推荐标准实现者提供浮点可扩展精度格式(<a href="http://en.wikipedia.org/wiki/Extended_precision" target="_blank">Extended precision</a>)，Intel x86处理器有FPU(float point unit)浮点运算处理器支持这种扩展。</p>
<p>非FPU的情况是用了SSE中128位寄存器(float实际只用了其中的32位，计算时也是以32位计算的)，这就是导致上述问题产生的最终原因。详细分析见文末说明。</p>
<p>知道了这一点，我们可以man g++ 看一下文档，我们可以找到一个编译选项叫：<strong>-mfpmath，在32位下，这个编译选项的默认值是：387，也就是x87 FPU指令，在64位下，这个编译选项的值是sse，也就是使用SSE的指令</strong>。所以，就这篇文章中的这个例子而言，如果你在64bits下加上如 -mfpmath=387，你会得到“正确的”结果，而不是“合理的”结果。</p>
<p>而在VS2012中C++，<a href="http://msdn.microsoft.com/zh-cn/library/vstudio/e7s85ffb(v=vs.110).aspx" target="_blank">编译选项可以设置(代码生成中)</a>可选，/fp:[precise | fast | strict]，本例中Release 32位下用precise 或者 strict将得到合理的结果(-202014160)，fast将产生正确的结果(-202014162), fast debug/release下结果也不一样哦(release下才优化了)。64系统下各个结果可以大家自己去测试下(Debug/Release)，分别看看VS编译后产生的中间代码长什么样。（陈皓注：我的VS2012在debug编译下，无论你怎么设置/fp的参数值，汇编都是一样的，使用SSE指令，而Release就不一样了，但是我的release下看代码的汇编非常怪异和源代码对上号，多年不用Windows开发了，对VS的使用仅停留在VC6++/VC2005上）</p>
<p>所以，我们在从x87 FPU指令向SSE指令做代码移植的时候，我们可能会遇到向这样的浮点数的精度问题，这个精度问题会多次科学计算中会更糟糕。<strong>这个问题并不简单的只是在32位和64位中的系统出算，这个问题主要还是看语言编译器的实现</strong>。在更为高级的语言中，如：C99或Fortran 2003中，引入了“long double”来做可扩展双精度（Extension Double），这样就可以消除更多的精度问题。</p>
<p>下面我们把程序改成long double，（注：其中的类型变成long double）</p>
<pre data-enlighter-language="c" class="EnlighterJSRAW">#include
using namespace std;

int main()
{
    long double p3x = 80838.0;
    long double p2y = -2499.0;
    long double v321 = p3x * p2y;
    std::cout.precision(15);
    std::cout &lt;&lt; v321 &lt;&lt; std::endl;

    return 0;
}</pre>
<p>用gdb的disassemble /m main你会看到其中的运算的汇编如下（使用了fmlp指令）：</p>
<pre data-enlighter-language="c" class="EnlighterJSRAW">//linux 32位系统
8	    long double v321 = p3x * p2y;
   0x08048633 &lt;+63&gt;:	fldt   0x10(%esp)
   0x08048637 &lt;+67&gt;:	fldt   0x20(%esp)
   0x0804863b &lt;+71&gt;:	fmulp  %st,%st(1)
   0x0804863d &lt;+73&gt;:	fstpt  0x30(%esp)
</pre>
<pre data-enlighter-language="c" class="EnlighterJSRAW">//linux 64位系统
8           long double v321 = p3x * p2y;
   0x0000000000400818 &lt;+52&gt;:    fldt   -0x30(%rbp)
   0x000000000040081b &lt;+55&gt;:    fldt   -0x20(%rbp)
   0x000000000040081e &lt;+58&gt;:    fmulp  %st,%st(1)
   0x0000000000400820 &lt;+60&gt;:    fstpt  -0x10(%rbp)
</pre>
<p><span style="line-height: 1.5em;">我们可以看到，32位系统和64位系统使用了同样的汇编指令（当然，我没有那么多物理机，我只是在VMWare Play的虚拟机上测试的，所以上面的示例并不一定适用于所有的地方，另外，C/C++语言和编译器和平台有非常大的关系） ，原因自然是我们用到了long double这个扩展双精度的数据类型。（注：如果你用double或float，在Linux上，32位用x87 FPU 指令编译，而64位用SSE指令编译）</span></p>
<p>好了，我们再回到C#上来，<span style="line-height: 1.5em;">C#的浮点是支持该标准的，其中</span><a style="line-height: 1.5em;" href="http://msdn.microsoft.com/en-us/library/aa691146(v=vs.71).aspx">其官方文档</a><span style="line-height: 1.5em;">也提到了浮点运算可能会产生比返回类型更高精度的值（正如上面的返回值精度就超过了float的精度），并说明如果硬件支持可扩展浮点精度的话，那么</span><strong style="line-height: 1.5em;">所有的</strong><span style="line-height: 1.5em;">浮点运算都将用此精度进行以提高效率，举个例子x*y/z, x*y的值可能都在double的能力范围之外了，但真实情况可能除以z后又能把结果拉回到double范围内，这样的话，用了FPU的结果就会得到一个准确的double值，而非FPU的就是无穷大之类的了。</span></p>
<p><span style="line-height: 1.5em;">所以，对于</span>C#来说，你显然无法找到一个像C/C++一样的利用编译器选项的来解决这个问题的“解决方案”（其实，用编译器参数是一个伪解决方案）<span style="line-height: 1.5em;">。</span></p>
<p><span style="line-height: 1.5em;"><strong>而且，要解决这个问题也不是要修改编译器选项，因为这个问题明显不是FPU或是SSE的问题，FPU是个过时的技术，SSE才是合理的技术，所以，<span style="color: #cc0000;">如果你不想你的浮点数在计算上有什么问题，而且你需要精度准确，正确的解决方案不是搞编译参数，而是——你一定要使用精度更高字节数更多的数据类型，比如：double 或是long double</span>。</strong></span></p>
<p>另外，大家在写代码的时候得保证实际运行环境/测试环境/开发环境的<strong>一致性(包括OS架构啊、编译选项等)</strong>啊（<strong>尤其是C/C++ 而且，编译器上的参数可能会有很多坑，而且有些坑可能会掩盖你程序中的问题</strong>），不然莫名其妙的问题会产生（本文就是开发环境与运行环境不一致导致的问题，纠结了好久才发现是这个原因）；遇到涉及浮点运算的时候别忘了有可能是这个原因产生的；<strong>float/double混用的情况得特别注意</strong>。</p>
<p><strong>Reference：</strong></p>
<p>[1] <a href="http://msdn.microsoft.com/en-us/library/aa691146(v=vs.71).aspx">C# Language Specification Floating point types</a><br />
[2] <a href="http://stackoverflow.com/questions/6683059/are-floating-point-numbers-consistent-in-c-can-they-be">Are floating-point numbers consistent in C#? Can they be? </a><br />
[3] <a href="http://www.plantation-productions.com/Webster/www.artofasm.com/Linux/HTML/RealArithmetica2.html">The FPU Instruction Set</a></p>
<h4><strong>附录</strong></h4>
<h5><strong>80838.0f * -2499.0f = -202014160.0浮点运算过程的说明</strong></h5>
<p>32位浮点数在计算机中的表示方式为：1位符号位(s)-8位指数位(E)-23位有效数字(M)。<br />
32位Float = (-1)^s * (1+m) * 2^(e-127), 其中e是实际转换成1.xxxxx*2^e的指数,m是前面的xxxxx(节约1位)</p>
<p>80838.0f = 1 0011 1011 1100 0110.0= 1.00111011110001100*2^16<br />
有效位M = 0011 1011 1100 0110 0000 000<br />
指数位E = 16 + 127 = 143 =  10001111<br />
内部表示 80838.0 =  0 [1000 1111] [0011 1011 1100 0110 0000 000]<br />
= 0100 0111 1001 1101 1110 0011 0000 0000<br />
= 47 9d e3 00 //实际调试时看到的内存值 可能是00 e3 9d 47是因为调试环境用了小端表示法法：低位字节排内存低地址端，高位排内存高地址</p>
<p>-2499.0 = -100111000011.0 = -1.001110000110 * 2^11<br />
有效位M = 0011 1000 0110 0000 0000 000<br />
指数位E = 11+127=138= 10001010<br />
符号位s = 1<br />
内部表示-2499.0 = 1 [10001010] [0011 1000 0110 0000 0000 000]<br />
=1100 0101 0001 1100 0011 0000 0000 0000<br />
=c5 1c 30 00</p>
<p>80838.0 * -2499.0 = ?</p>
<p>首先是指数 e = 11+16 = 27<br />
指数位E = e + 127 = 154 = 10011010<br />
有效位相乘结果为 1.1000 0001 0100 1111 1011 1010 01 //可以自己动手实际算下<br />
实际中只能有23位，后面的被截断即1000 0001 0100 1111 1011 101<span style="text-decoration: line-through;">0 01 </span><br />
相乘结果内部表示=1[10011010][1000 0001 0100 1111 1011 101]<br />
= 1100 1101 0100 0000 1010 0111 1101 1101<br />
= cd 40 a7 dd</p>
<p>结果 =  -1.1000 0001 0100 1111 1011 101 *2^27<br />
=  -11000 0001 0100 1111 1011 1010000<br />
=  -202014160<br />
再转成double后还是-202014160.</p>
<p>如果是FPU的话，上面的有效位结果不会被截断，即<br />
FPU结果 = -1.1000 0001 0100 1111 1011 101<strong>001</strong> *2^27<br />
= -11000 0001 0100 1111 1011 101<strong>001</strong>0<br />
= -202014162</p>
<p>全文完，若本文有纰漏之处欢迎指正。<!--



<p align="center"><a href= target=_blank><img decoding="async" src=""></a></p>





<p align="center"><img decoding="async" src="https://coolshell.cn/wp-content/uploads/2020/03/coolshell.weixin.jpg"> <img decoding="async" loading="lazy" src="https://coolshell.cn/wp-content/uploads/2020/03/coolshell.mini_.jpg" width="300" height="300"> <br />关注CoolShell微信公众账号和微信小程序</p>

 

--></p>
<div style="margin-top: 15px; font-size: 16px;color: #cc0000;">
<p align="center"><strong>（转载本站文章请注明作者和出处 <a href="https://coolshell.cn/">酷 壳 &#8211; CoolShell</a> ，请勿用于任何商业用途）</strong></p>
</div>

<div class="wp_rp_wrap  wp_rp_vertical_m" id="wp_rp_first"><div class="wp_rp_content"><h3 class="related_post_title">相关文章</h3><ul class="related_post wp_rp"><li ><a href="https://coolshell.cn/articles/3008.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/plugins/wordpress-23-related-posts-plugin/static/thumbs/10.jpg" alt="Windows编程革命简史" width="150" height="150" /></a><a href="https://coolshell.cn/articles/3008.html" class="wp_rp_title">Windows编程革命简史</a></li><li ><a href="https://coolshell.cn/articles/2672.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/plugins/wordpress-23-related-posts-plugin/static/thumbs/0.jpg" alt=".NET代码转换器" width="150" height="150" /></a><a href="https://coolshell.cn/articles/2672.html" class="wp_rp_title">.NET代码转换器</a></li><li ><a href="https://coolshell.cn/articles/20845.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2020/03/rust-social-wide-150x150.jpg" alt="Rust语言的编程范式" width="150" height="150" /></a><a href="https://coolshell.cn/articles/20845.html" class="wp_rp_title">Rust语言的编程范式</a></li><li ><a href="https://coolshell.cn/articles/18360.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2018/05/300x262-150x150.jpg" alt="程序员练级攻略（2018)  与我的专栏" width="150" height="150" /></a><a href="https://coolshell.cn/articles/18360.html" class="wp_rp_title">程序员练级攻略（2018)  与我的专栏</a></li><li ><a href="https://coolshell.cn/articles/18024.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2017/07/api-design-300x278-2-150x150.jpg" alt="API设计原则 &#8211; Qt官网的设计实践总结" width="150" height="150" /></a><a href="https://coolshell.cn/articles/18024.html" class="wp_rp_title">API设计原则 &#8211; Qt官网的设计实践总结</a></li><li ><a href="https://coolshell.cn/articles/12052.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/plugins/wordpress-23-related-posts-plugin/static/thumbs/29.jpg" alt="Leetcode 编程训练" width="150" height="150" /></a><a href="https://coolshell.cn/articles/12052.html" class="wp_rp_title">Leetcode 编程训练</a></li></ul></div></div>The post <a href="https://coolshell.cn/articles/11235.html">一个浮点数跨平台产生的问题</a> first appeared on <a href="https://coolshell.cn">酷 壳 - CoolShell</a>.]]></content:encoded>
					
					<wfw:commentRss>https://coolshell.cn/articles/11235.html/feed</wfw:commentRss>
			<slash:comments>25</slash:comments>
		
		
			</item>
		<item>
		<title>.NET代码转换器</title>
		<link>https://coolshell.cn/articles/2672.html</link>
					<comments>https://coolshell.cn/articles/2672.html#comments</comments>
		
		<dc:creator><![CDATA[陈皓]]></dc:creator>
		<pubDate>Tue, 20 Jul 2010 02:24:22 +0000</pubDate>
				<category><![CDATA[.NET编程]]></category>
		<category><![CDATA[杂项资源]]></category>
		<category><![CDATA[编程工具]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[VB.NET]]></category>
		<guid isPermaLink="false">http://coolshell.cn/?p=2672</guid>

					<description><![CDATA[<p>想把.NET的代码（C#和VB.NET)互转吗？或是转成Python或Ruby吗？在 http://www.developerfusion.com/ 站点上有这...</p>
<p class="read-more"><a class="btn btn-default" href="https://coolshell.cn/articles/2672.html"> Read More<span class="screen-reader-text">  Read More</span></a></p>
The post <a href="https://coolshell.cn/articles/2672.html">.NET代码转换器</a> first appeared on <a href="https://coolshell.cn">酷 壳 - CoolShell</a>.]]></description>
										<content:encoded><![CDATA[<p><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3415450859608158"
     crossorigin="anonymous"></script>想把.NET的代码（C#和VB.NET)互转吗？或是转成Python或Ruby吗？在 <a href="http://www.developerfusion.com/" target="_blank">http://www.developerfusion.com/</a> 站点上有这样的在线工具。点击下面的链接你可以使用这些工具。当然，这些工具也有很多<a href="http://feedback.developerfusion.com/pages/code_converter" target="_blank">BUG</a>。</p>
<ul>
<li><a href="http://www.developerfusion.com/tools/convert/csharp-to-vb/" target="_blank">把 C# 转成 VB.NET</a></li>
<li><a href="http://www.developerfusion.com/tools/convert/csharp-to-python/" target="_blank">把 C# 转成 Python</a></li>
<li><a href="http://www.developerfusion.com/tools/convert/csharp-to-ruby/" target="_blank">把 C# 转成Ruby</a></li>
<li><a href="http://www.developerfusion.com/tools/convert/vb-to-csharp/" target="_blank">把 VB.NET 转成C#</a></li>
<li><a href="http://www.developerfusion.com/tools/convert/vb-to-python/" target="_blank">把 VB.NET 转成 Python</a></li>
<li><a href="http://www.developerfusion.com/tools/convert/vb-to-ruby/" target="_blank">把 VB.NET 转成 Ruby</a></li>
</ul>
<p>老实说，我并不太清楚这些工具有什么用，看似很useless。难道是为了用来学习新的语言？就像Google的Translator的一样？就像一个并不懂中文的老外可以用Google Translator在其Facebook中整点中文耍耍酷一样，难道说，一个C#的程序员可以用这样的工具和一个Python的程序员也耍耍酷？各位看客觉得这个东西有意义吗？</p>
<p>不过，有一点我可以确定，如果有工具把Unix/Linux下的C源码和Windows下的C源码相互自动转换，估计这会是相当划时代的，因为，这应该会让那些什么Wine或Cygwin之类的东西都统统会成为历史了。不过，这样的东西在实现上又将会有多么大的难度（OS系统API的相互转换），这个事会有可行性吗？<!--



<p align="center"><a href= target=_blank><img decoding="async" src=""></a></p>





<p align="center"><img decoding="async" src="https://coolshell.cn/wp-content/uploads/2020/03/coolshell.weixin.jpg"> <img decoding="async" loading="lazy" src="https://coolshell.cn/wp-content/uploads/2020/03/coolshell.mini_.jpg" width="300" height="300"> <br />关注CoolShell微信公众账号和微信小程序</p>

 

--></p>
<div style="margin-top: 15px; font-size: 16px;color: #cc0000;">
<p align="center"><strong>（转载本站文章请注明作者和出处 <a href="https://coolshell.cn/">酷 壳 &#8211; CoolShell</a> ，请勿用于任何商业用途）</strong></p>
</div>

<div class="wp_rp_wrap  wp_rp_vertical_m" ><div class="wp_rp_content"><h3 class="related_post_title">相关文章</h3><ul class="related_post wp_rp"><li ><a href="https://coolshell.cn/articles/11235.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/plugins/wordpress-23-related-posts-plugin/static/thumbs/2.jpg" alt="一个浮点数跨平台产生的问题" width="150" height="150" /></a><a href="https://coolshell.cn/articles/11235.html" class="wp_rp_title">一个浮点数跨平台产生的问题</a></li><li ><a href="https://coolshell.cn/articles/3192.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2010/10/Intel-Recommended-Books-for-Developers-150x150.jpg" alt="一些非常不错的资料" width="150" height="150" /></a><a href="https://coolshell.cn/articles/3192.html" class="wp_rp_title">一些非常不错的资料</a></li><li ><a href="https://coolshell.cn/articles/3008.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/plugins/wordpress-23-related-posts-plugin/static/thumbs/10.jpg" alt="Windows编程革命简史" width="150" height="150" /></a><a href="https://coolshell.cn/articles/3008.html" class="wp_rp_title">Windows编程革命简史</a></li><li ><a href="https://coolshell.cn/articles/20845.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2020/03/rust-social-wide-150x150.jpg" alt="Rust语言的编程范式" width="150" height="150" /></a><a href="https://coolshell.cn/articles/20845.html" class="wp_rp_title">Rust语言的编程范式</a></li><li ><a href="https://coolshell.cn/articles/18360.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2018/05/300x262-150x150.jpg" alt="程序员练级攻略（2018)  与我的专栏" width="150" height="150" /></a><a href="https://coolshell.cn/articles/18360.html" class="wp_rp_title">程序员练级攻略（2018)  与我的专栏</a></li><li ><a href="https://coolshell.cn/articles/18024.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2017/07/api-design-300x278-2-150x150.jpg" alt="API设计原则 &#8211; Qt官网的设计实践总结" width="150" height="150" /></a><a href="https://coolshell.cn/articles/18024.html" class="wp_rp_title">API设计原则 &#8211; Qt官网的设计实践总结</a></li></ul></div></div>The post <a href="https://coolshell.cn/articles/2672.html">.NET代码转换器</a> first appeared on <a href="https://coolshell.cn">酷 壳 - CoolShell</a>.]]></content:encoded>
					
					<wfw:commentRss>https://coolshell.cn/articles/2672.html/feed</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>初学C#编程的注意事项</title>
		<link>https://coolshell.cn/articles/1375.html</link>
					<comments>https://coolshell.cn/articles/1375.html#comments</comments>
		
		<dc:creator><![CDATA[陈皓]]></dc:creator>
		<pubDate>Mon, 31 Aug 2009 04:15:05 +0000</pubDate>
				<category><![CDATA[.NET编程]]></category>
		<category><![CDATA[编程语言]]></category>
		<category><![CDATA[C++]]></category>
		<guid isPermaLink="false">http://coolshell.cn/?p=1375</guid>

					<description><![CDATA[<p>下面是8个C#编程时的注意事项是给初学者的，可能你知道，也可能你不知道，不过这些都是一些可能会让人疏忽的地方，还是要注意一下。 1.使用String变量: 考虑...</p>
<p class="read-more"><a class="btn btn-default" href="https://coolshell.cn/articles/1375.html"> Read More<span class="screen-reader-text">  Read More</span></a></p>
The post <a href="https://coolshell.cn/articles/1375.html">初学C#编程的注意事项</a> first appeared on <a href="https://coolshell.cn">酷 壳 - CoolShell</a>.]]></description>
										<content:encoded><![CDATA[<p><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3415450859608158"
     crossorigin="anonymous"></script>下面是8个C#编程时的注意事项是给初学者的，可能你知道，也可能你不知道，不过这些都是一些可能会让人疏忽的地方，还是要注意一下。</p>
<p><strong>1.使用String变量:</strong></p>
<p>考虑有下面的一个程序想判断一下字符串是否有内容。</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
if (someString.Length &gt; 0)
{
    // …
}
</pre>
<p>但是，这个字符串对象很可能是个空对象，所以，最好先判断一下null</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
if  (!String.IsNullOrEmpty(someString))
{
    // 是不是更好一些？
}
</pre>
<p><span id="more-1375"></span></p>
<p><strong>2.字符器连接</strong></p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
string s = “dev”;
s += “-”;
s += “the”;
s += “-”;
s += “web”;
s += “.”;
s += “com”;
</pre>
<p>这样做没什么问题，只不过性能不高，因为+=操作符其实调用的是String类的Append访问，所以，+=会有两次函数调用，下面的则会好一些。</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
StringBuilder s = new StringBuilder();
s.Append(”dev”);
s.Append(”-”);
s.Append(”the”);
s.Append(”-”);
s.Append(”web”);
s.Append(”.”);
s.Append(”com”);
</pre>
<p><strong>3.使用Console</strong></p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
Console.WriteLine(&quot;A= &quot; + 1 + &quot; B=&quot; + 2 + &quot; C= &quot; + someValue);
</pre>
<p>和第二点说的一样，这并没有效率，使用下面的语句，会更有效率。</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
Console.WriteLine(”A: {0}\nB: {1}\nC: {2}”, 1, 2, someValue);
</pre>
<p><strong>4.字符串转整型</strong></p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
int i = int.Parse(Request.QueryString[&quot;id&quot;]);
</pre>
<p>这样做的问题是，如果有人这样请求你的页面：yourpage.aspx?id=A6，那么A6将会导致你的程序抛出一个异常。因为A6不是一个整数字符串。使用TryParse会好一点。</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
int i;
if (!int.TryParse(Request.QueryString[&quot;id&quot;] , out i))
{
    //…
}
</pre>
<p><strong>5. 调用IDbConnection 的 Close 方法</strong></p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
IDbConnection dbConn = null;

try
{
    dbConn = new SqlConnection(”some Connection String”);
    dbConn.Open();
}
finally
{
    dbConn.Close();
}
</pre>
<p>调用SqlConnection的构造函数可能会出现一个异常，如果是这样的话，我们还需要调用Close方法吗？</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
IDbConnection dbConn = null;

try
{
    dbConn = new SqlConnection(”Some Connection String”);
    dbConn.Open();
}
finally
{
    if (dbConn != null)
    {
        dbConn.Close();
    }
}
</pre>
<p><strong>6.使用List类</strong></p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
public void SomeMethod(List&lt;SomeItem&gt; items)
{
    foreach(var item in items)
    {
        // do something with the item…
    }
}
</pre>
<p>如果我们只是遍历List容器中的所有内容的话，那么，使用IEnumerable接口会更好一些。因为函数参数传递一个List对象要比一个IEnumerable接口要花费更多的开销。</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
public void SomeMethod(IEnumerable&lt;SomeItem&gt; items)
{
    foreach(var item in items)
    {
        // do something with the item…
    }
}
</pre>
<p><strong>7.直接使用数字</strong></p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
if(mode == 1) { … }
else if(mode == 2) { … }
else if(mode == 3) { … }
</pre>
<p>为什么不给你的这些数字取个名字呢？比如使用Enumerations。</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
public enum SomeEnumerator
{
    DefaultMode = 1,
    SafeMode = 2,
    NormalMode = 3
}

if(mode == SomeEnumerator.DefaultMode) { … }
else if(mode == SomeEnumerator.SafeMode) { … }
else if(mode == SomeEnumerator.NormalMode) { … }
</pre>
<p><strong>8.字符串替换</strong></p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
string s = &quot;www.coolshell.cn is a amazing site&quot;;
s.Replace(&quot;amazing&quot;, &quot;awful&quot;);
</pre>
<p>字符串s的内容什么也不会改变，因为string返回的是替换过的字串。这点很多初学者经常忘了。下面就没有问题了。</p>
<pre data-enlighter-language="csharp" class="EnlighterJSRAW">
s = s.Replace(&quot;amazing&quot;, &quot;awful&quot;);
</pre>
<p>文章：<a href="http://dev-the-web.com/blog/2009/08/27/top-csharp-programming-mistakes/" target="_blank">来源</a><!--



<p align="center"><a href= target=_blank><img decoding="async" src=""></a></p>





<p align="center"><img decoding="async" src="https://coolshell.cn/wp-content/uploads/2020/03/coolshell.weixin.jpg"> <img decoding="async" loading="lazy" src="https://coolshell.cn/wp-content/uploads/2020/03/coolshell.mini_.jpg" width="300" height="300"> <br />关注CoolShell微信公众账号和微信小程序</p>

 

--></p>
<div style="margin-top: 15px; font-size: 16px;color: #cc0000;">
<p align="center"><strong>（转载本站文章请注明作者和出处 <a href="https://coolshell.cn/">酷 壳 &#8211; CoolShell</a> ，请勿用于任何商业用途）</strong></p>
</div>

<div class="wp_rp_wrap  wp_rp_vertical_m" ><div class="wp_rp_content"><h3 class="related_post_title">相关文章</h3><ul class="related_post wp_rp"><li ><a href="https://coolshell.cn/articles/20845.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2020/03/rust-social-wide-150x150.jpg" alt="Rust语言的编程范式" width="150" height="150" /></a><a href="https://coolshell.cn/articles/20845.html" class="wp_rp_title">Rust语言的编程范式</a></li><li ><a href="https://coolshell.cn/articles/18360.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2018/05/300x262-150x150.jpg" alt="程序员练级攻略（2018)  与我的专栏" width="150" height="150" /></a><a href="https://coolshell.cn/articles/18360.html" class="wp_rp_title">程序员练级攻略（2018)  与我的专栏</a></li><li ><a href="https://coolshell.cn/articles/18024.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2017/07/api-design-300x278-2-150x150.jpg" alt="API设计原则 &#8211; Qt官网的设计实践总结" width="150" height="150" /></a><a href="https://coolshell.cn/articles/18024.html" class="wp_rp_title">API设计原则 &#8211; Qt官网的设计实践总结</a></li><li ><a href="https://coolshell.cn/articles/12052.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/plugins/wordpress-23-related-posts-plugin/static/thumbs/29.jpg" alt="Leetcode 编程训练" width="150" height="150" /></a><a href="https://coolshell.cn/articles/12052.html" class="wp_rp_title">Leetcode 编程训练</a></li><li ><a href="https://coolshell.cn/articles/12012.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2014/10/edsm-150x150.gif" alt="State Threads 回调终结者" width="150" height="150" /></a><a href="https://coolshell.cn/articles/12012.html" class="wp_rp_title">State Threads 回调终结者</a></li><li ><a href="https://coolshell.cn/articles/11466.html" class="wp_rp_thumbnail"><img src="https://coolshell.cn/wp-content/uploads/2014/04/c99-150x150.jpg" alt="C语言的整型溢出问题" width="150" height="150" /></a><a href="https://coolshell.cn/articles/11466.html" class="wp_rp_title">C语言的整型溢出问题</a></li></ul></div></div>The post <a href="https://coolshell.cn/articles/1375.html">初学C#编程的注意事项</a> first appeared on <a href="https://coolshell.cn">酷 壳 - CoolShell</a>.]]></content:encoded>
					
					<wfw:commentRss>https://coolshell.cn/articles/1375.html/feed</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
	</channel>
</rss>
