【问题标题】:what is the value that is passing into the called method when "out paramater" is passed传递“输出参数”时传递给被调用方法的值是什么
【发布时间】:2017-12-21 09:49:21
【问题描述】:
static void Main(string[] args)
{
    int i = 10;

    Program th = new Program();

    Thread t2 = new Thread(() => thread2(out i));
    t2.Start();
    Thread t1 = new Thread(() => thread1(i));
    t1.Start();
    Thread.Sleep(5000);

    Console.WriteLine("Main thread exits." + i);
    Console.ReadLine();
}

static void thread1(int i)
{
    Console.WriteLine(i);
    i = 100;
}

static void thread2(out int i) // what should be the value of i???
{
    Thread.Sleep(5000);
    i = 21;           
    Console.WriteLine(i);
}

当我们传递参数时,在被调用方法中接收到的值应该是什么? “无论是零还是我们传递的值”

【问题讨论】:

  • 你试过运行这段代码吗?发生了什么?
  • 你问out参数是什么?
  • 勾选的答案here会有所帮助
  • 我不明白你的问题。在离开方法之前,您必须给每个输出参数一个值。或者你是在问哪个i会被thread2修改?试试看,你会看到。
  • 谢谢大家,我的问题得到了答案

标签: c# .net parameters out


【解决方案1】:

根据你的代码

static void Main(string[] args)
{
    int i = 10;

    Program th = new Program();

    Thread t2 = new Thread(() => thread2(out i));
    t2.Start();
    Thread t1 = new Thread(() => thread1(i));
    t1.Start();
    Thread.Sleep(5000);

    Console.WriteLine("Main thread exits." + i);
    Console.ReadLine();
}

第一个函数 thread2 将收到值 i = 10 。但是

在第二个函数中,您将收到 i =10 or i =21 ,因为它完全取决于在 CLR/CPU 级别完成的执行。

我的意思是,如果你在 thread1() 执行之前完成了 thread2() 方法执行,那么 thread1() 将收到 21。但如果执行未完成,则接收10 作为输入。

如果您从 thread2() 函数中删除此行 Thread.Sleep(5000);,则上述情况为真。

但是如果你没有超过 10 将被传递给函数和主线程 print 10 在理想情况下,但这也取决于上下文切换......你的输出在这里不固定。一切都在处理和执行上。

【讨论】:

    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 2015-04-17
    • 2016-06-07
    • 2014-04-11
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2012-02-03
    相关资源
    最近更新 更多