gpt4 book ai didi

c# - 在没有引用的情况下传递类实例

转载 作者:太空狗 更新时间:2023-10-30 00:03:21 27 4
gpt4 key购买 nike

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

案例 1:像 int 这样的简单 var:

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++;
}

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

案例二:类:

// 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);
}

而且,正如代码评论中所写,我没有通过我的 cTest 作为引用,但结果是一样的,消息显示 55 而不是 2..

如何在没有引用的情况下通过类(class)?

最佳答案

How can I pass a class without reference?

你不能。

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

  • 类 - 引用类型
  • struct - 值类型。

阅读:

引用 Jon Skeet C# in depth second edition :

MYTH #3: “OBJECTS ARE PASSED BY REFERENCE IN C# BY DEFAULT”

This is probably the most widely propagated myth. Again, the people who make thisclaim often (though not always) know how C# actually behaves, but they don’t knowwhat “pass by reference” really means. Unfortunately, this is confusing for people whodo know what it means. The formal definition of pass by reference is relatively complicated,involving l-values and similar computer science terminology, but the importantthing is that if you pass a variable by reference, the method you’re calling can changethe value of the caller’s variable by changing its parameter value. Now remember that thevalue of a reference type variable is the reference, not the object itself. You can changethe contents of the object that a parameter refers to without the parameter itself beingpassed by reference.For instance, the following method changes the contents of theStringBuilder object in question, but the caller’s expression will still refer to thesame object as before:

void AppendHello(StringBuilder builder)
{
builder.Append("hello");
}

When this method is called, the parameter value (a reference to a StringBuilder) ispassed by value. If I were to change the value of the builder variable within themethod—for example, with the statement builder = null;—that change wouldn’t beseen by the caller, contrary to the myth.

深入了解 C# 值类型和引用类型第 46 页

关于c# - 在没有引用的情况下传递类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11221000/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com