传递类实例而不引用

ghi*_*boz 5 c# reference ref pass-by-reference

我有关于通过ref传递一些实例的问题:这是我的问题:

案例1:简单的var类似int:

private void button2_Click(object sender, EventArgs e)
{
    int nTest = 10;

    testInt(nTest);
    MessageBox.Show(nTest.ToString());
    // this message show me 10

    testIntRef(ref nTest);
    MessageBox.Show(nTest.ToString());
    // this message show me 11
}

private void testInt(int nn)
{
    nn++;
}

private void testIntRef(ref int nn)
{
    nn++;
}
Run Code Online (Sandbox Code Playgroud)

这正是我的想法,如果我使用ref,参数是通过引用传递的,所以如果更改,当我退出函数时,值会被更改...

案例2:课程:

// simple class to understand the reference..
public class cTest
{
    int nTest;
    public cTest()
    {
        setTest(0);
    }

    public void setTest(int n)
    {
        nTest = n;
    }

    public int getTest()
    {
        return nTest;
    }
}

// my main code
private void button3_Click(object sender, EventArgs e)
{
    cTest tt = new cTest();
    tt.setTest(2);

    testClass(tt);

    // I expect that the message shows me 2, 'cause testClass
    // doesn't have (ref cTest test)
    MessageBox.Show(tt.getTest().ToString());
}

private void testClass(cTest test)
{
    test.setTest(55);
}
Run Code Online (Sandbox Code Playgroud)

并且,如在代码注释中所写,我没有通过我的cTest作为参考,但结果是相同的,消息显示我55而不是2 ..

如何在没有参考的情况下传递课程?

gdo*_*ica 12

如何在没有参考的情况下传递课程?

你不能.

您可以克隆该实例并发送它,但它仍将由ref发送...

  • class - 引用类型
  • struct - 值类型.

读:

引用Jon Skeet C#深度第二版:

神话#3:"C#中默认通过参考对象"

这可能是最广泛传播的神话.同样,提出此声明的人经常(虽然并不总是)知道C#的实际行为,但他们不知道"通过引用传递"的真正含义.不幸的是,对于那些知道它意味着什么的人来说,这是令人困惑的.通过引用传递的形式化定义相对复杂,涉及l值和类似的计算机科学术语,但重要的是如果通过引用传递变量,则您调用的方法可以通过以下方式更改调用方变量的值:更改其参数值.现在请记住,引用类型变量的值是引用,而不是对象本身.您可以更改参数引用的对象的内容,而不通过引用传递参数本身.例如,以下方法更改了相关StringBuilder对象的内容 ,但调用者的表达式仍将引用与以前相同的对象:

void AppendHello(StringBuilder builder)
{
    builder.Append("hello");
}
Run Code Online (Sandbox Code Playgroud)

调用此方法时,将通过值传递参数值(对StringBuilder的引用).如果我要在方法中更改构建器变量的值 - 例如,使用语句builder = null; - 调用者将看不到更改,与神话相反.

C#in depth值类型和引用类型第46页