对此C#代码行不确定 [英] Uncertain about this c# code line

查看:83
本文介绍了对此C#代码行不确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码行是否有隐藏的错误?
//检查A行

Could this code line has a hidden error ?
//check line A

main()
{	double x;
	x=4;

	// note two equal refrenced. i got good answer but
	// i  have to be sure
	ReWriteX(ref x,ref x);//<-------- Line A
}

private void ReWriteX(ref double x,ref double y)
{
	x=y*y*3.1415;
}

推荐答案

在这种情况下没有什么特别的,但是它说明了ref的滥用.
这是一种传递参数的输入/输出方法.您应该在方法的实现内部读取实际参数,并通过引用更新值.您要做的是:您不输入x,仅输出,您不修改y,仅读取其值.假设语义已由表达式x=y*y*3.1415;正确定义,则您的签名应为:

There is nothing special in this case, but it illustrates the misuse of ref.

This is an in-out method of passing parameters. You are supposed to read actual parameter inside the implementation of the method and update the value through the reference. What you do is: you don''t input x, only output, and you don''t modify y, only read its value. Assuming the semantic is correctly defined by the expression x=y*y*3.1415;, your signature should be:

static double ReWriteX(double y) { return y*y*3.1415; }



您的每个ref都会出现设计错误!

现在,对于调用而言,在期望两个不同的地方使用相同的引用当然是非常不安全的,但是严格来讲,这不是错误.您只会得到意想不到的结果.代码将读取两次相同的值(我的意思是,如果您确实使用了两个值),则它们将通过引用两次更新该值(我的意思是,如果您确实要更新两个值),而最终值是根据最后一次分配中使用的参考进行分配,这会产生不确定性.在您的确切代码中,一切都是可以预测的:您得到了4 * 4 * 3.1415.

—SA



Each of your ref would be a design error!

Now, as to the call, using identical reference where two different are expected is of course very unsafe, but this is, strictly speaking, not a bug. You only can get an unexpected result. The code would read the same value twice (I mean, if you really use both values), them you update the value through the reference twice (I mean, if you really update both values as it should be), and the final value is assigned from the reference which was used in the very last assignment, which creates uncertainty. In your exact code, everything is predictable: you got 4*4*3.1415.

—SA


ReWriteX 的方法签名清楚地提到了x的int类型.
您已将x定义为值为3.1415的double .

因此,您将得到一个错误.将方法签名中x的类型更改为double.
The method signature for ReWriteX clearly mentions type int for x.
You have defined x to be a double with value 3.1415.

Thus, you will get an error. Change type of x in the method signature to double.


这篇关于对此C#代码行不确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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