110,539
社区成员
发帖
与我相关
我的任务
分享
class MyProc
{
public void Calc(ref int count)
{
Interlocked.Increment(ref count);
Thread.Sleep(100);
}
}
class testref
{
private int count;
public testref()
{
count = 0;
}
public void test()
{
for (int i = 0; i < 10; i++)
{
Interlocked.Increment(ref count);
MyProc proc = new MyProc();
//就是不知道下一句里的第二个参数怎么构造才能从proc.Calc里引用count
ThreadPool.QueueUserWorkItem(new WaitCallback(proc.Calc), ref count);
}
MessageBox.Show("Count=" + count.ToString());
Thread.Sleep(2000);
MessageBox.Show("Count=" + count.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
testref t = new testref();
t.test();
}
void Calc(ref int x)
{
x = 3;
}
void test()
{
value = 0;
Calc(ref value);
Debug.Assert(value == 3);
}
这能说“方法 Calc 内部把外部变量value给改为3”了吗?如果你老是那样教你,就是非常明显在瞎说了!没有一个正规的说明敢说“ref的意思就是方法内部去修改方法外部的变量值”。如果是你自己瞎猜的,那么情有可原,实际情况完全不是这么回事。ref 的意思是说 Calc 执行结束之后会把结果赋值给 value,而绝不是说 Calc 内部会去修改外部变量 value。
高级语言不胡乱解释什么参数上的 ref 的作用,去掉了c语言的胡乱之源。这是各种高级语言跟 c 的重要区别。public void Calc(int input, Action<int> callback)
这样设计接口!
class MyProc
{
public void Calc(object state)
{
((testref)state).IncreaseCount();
Thread.Sleep(100);
}
}
class testref
{
private int count;
public void test()
{
for (int i = 0; i < 10; i++)
{
IncreaseCount();
MyProc proc = new MyProc();
ThreadPool.QueueUserWorkItem(new WaitCallback(proc.Calc), this);
}
// ...
}
public void IncreaseCount()
{
Interlocked.Increment(ref count);
}
}
或者:
class MyProc
{
public void Calc(object state)
{
((Action)state)();
Thread.Sleep(100);
}
}
class testref
{
private int count;
public void test()
{
for (int i = 0; i < 10; i++)
{
Interlocked.Increment(ref count);
MyProc proc = new MyProc();
ThreadPool.QueueUserWorkItem(new WaitCallback(proc.Calc), new Action(() => Interlocked.Increment(ref count)));
}
// ...
}
}