gpt4 book ai didi

c# - 可以引用一下吗?

转载 作者:行者123 更新时间:2023-12-02 10:46:37 24 4
gpt4 key购买 nike

您能否传递对引用类型的引用来了解传递控件的行为方式?

我注意到,当您将一个控件传递给构造函数时,它实际上传递了对该控件的引用,然后如果您将另一个控件分配给该控件,它不会复制该值,而是实际上复制引用本身!为什么不能使用常规变量或至少使用 ref 关键字来完成此操作?

例如...

public class Test : Form
{

Test()
{
InitializeComponent();
}
Test_Load(object sender, EventArgs e)
{
new Test2((Control)MyTextBox).ShowDialog();
}

}

public class Test2 : Form
{
Public Control x_
Test2(Control x)
{
x_=x;
InitializeComponent();
}
//use x_ somewhere in code to actually change x
}

我不明白的是,这适用于控件,但不适用于其他变量。现在假设我将 x 作为 int ref 传递,我无法将 ref 本身传递给 x_ 吗?在控件的情况下,我什至不必使用 ref 这让我困惑,这到底是如何发生的......我知道如何通过方法和父/所有者来回传递变量,所以我的问题非常具体特殊的准指针。也许我误解了传递 Control 的行为方式,如果是这种情况,您将如何像 Control 一样构造 int ,以便当您将 int 分配给像 Control 这样的 int 时,它会更改原始 int 就像更改原始 Control 一样.

这有效。发送与发送相同。

    new InputBox(((Label)sender)).ShowDialog();

Label Send;
public InputBox(Label send)
{
Send=send;
}

我希望它能以同样的方式工作。现在,发送与发送相同,但并不完全相同。

    new InputBox(((string)sender)).ShowDialog();

string Send;
public InputBox(string send)
{
Send=send;
}

我知道如何在类之间传递变量等,但我要求具体让一个字符串的行为方式与 Label 在传递时的行为方式相同。当它被传递时,它的传递与指针完全相同,因为我可以使变量等于该变量的同一实例。为什么我不能使一个字符串等于该字符串的同一个实例?

最佳答案

我认为你需要理解的是 Value Types and Reference Types 之间的区别

Value Types

A data type is a value type if it holds the data within its own memoryallocation.

它们包括以下类型

  • 所有数字数据类型
  • bool 值、字符和日期
  • 所有结构,即使其成员是引用类型
  • 枚举,因为它们的基础类型始终是 SByte、Short、Integer、Long、Byte、UShort、UInteger 或 ULong

Reference Types

A reference type contains a pointer to another memory location thatholds the data.

它们包括以下类型

  • 字符串
  • 所有数组,即使它们的元素是值类型
  • 类类型,例如 Form
  • 代表

ref (C# Reference)更远

The ref keyword causes an argument to be passed by reference, not byvalue. The effect of passing by reference is that any change to theparameter in the method is reflected in the underlying argumentvariable in the calling method.

这解释了为什么如果您希望将值类型的更改传播到 collung 方法,则需要更改方法签名以使用 ref。

这是一个有关构造函数调用的示例

Control c1 = null;
Class1 cl1 = new Class1(c1); //c1 is still null after this call
Control c2 = null;
Class1 cl2 = new Class1(ref c2); //c2 is NOT null after this call

class Class1
{
public Class1(Control c)
{
c = new Control();
}

public Class1(ref Control c)
{
c = new Control();
}
}

关于c# - 可以引用一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17017295/

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