gpt4 book ai didi

c# - 为什么C#对象的行为一次类似于按值传递,而一次按引用传递?

转载 作者:太空宇宙 更新时间:2023-11-03 18:09:05 25 4
gpt4 key购买 nike

我不了解将参数传递给C#中的方法的一件事。从我看到的情况来看,c#中的对象有时的行为就像是通过引用传递的,一次就像是通过值传递的。在这段代码中,我按引用传递给method(),按值传递一次。这两个都按预期执行。但是当我创建Update()并按值传递对象时,我看到它的行为就像是在更新原始对象。

为什么我要用Update(myString input)更新原始对象,而不用method(myString input)更新它?

这是不合逻辑的!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassPassing
{
class Program
{
static void Main(string[] args)
{
myString zmienna = new myString();

Update(zmienna);
Console.WriteLine(zmienna.stringValue);
Console.WriteLine(zmienna.stringValue2);
Console.ReadLine();

zmienna.stringValue = "This has run in main";
zmienna.stringValue2 = "This is a help string";

method(zmienna);
Console.WriteLine(zmienna.stringValue);
Console.WriteLine(zmienna.stringValue2);
Console.ReadLine();

method(ref zmienna);
Console.WriteLine(zmienna.stringValue);
Console.WriteLine(zmienna.stringValue2);

Console.ReadLine();
}

static void method(myString input)
{
input = new myString();
}

static void method(ref myString input)
{
input = new myString();
}

static void Update(myString input)
{
input.stringValue2 = "This has run in update method";
}
}

public class myString
{
public string stringValue { get; set; }
public string stringValue2 { get; set; }

public myString() { stringValue = "This has been just constructed"; this.stringValue2 = "This has been just constructed"; }
}


}`

最佳答案

您必须了解您的代码:

static void method(myString input)
{
input = new myString();
}


在这里,您按值传递对对象的引用

static void method(ref myString input)
{
input = new myString();
}


在这里,您通过引用将引用传递给对象

static void Update(myString input)
{
input.stringValue2 = "This has run in update method";
}


在这里,您再次按值传递对对象的引用

现在:


当按值传递对象引用时,可以更改对象的内容,但不能更改引用本身(将其分配给另一个对象)。
通过引用传递对象引用时,您既可以更改对象的内容,也可以修改引用本身(将其分配给另一个对象)。


仅在简单(int,float等)类型和 struct情况下,C#中的按值传递才发生:

class Program 
{
public struct MyStruct
{
public int i;
}

public class MyClass
{
public int i;
}

public static void Modify(MyStruct s)
{
s.i = 99;
}

public static void Modify(MyClass c)
{
c.i = 99;
}

public static void Main(string[] args)
{
MyStruct myStruct = new MyStruct();
myStruct.i = 20;
MyClass myClass = new MyClass();
myClass.i = 20;

Modify(myStruct);
Modify(myClass);

Console.WriteLine("MyStruct.i = {0}", myStruct.i);
Console.WriteLine("MyClass.i = {0}", myClass.i);

Console.ReadKey();
}
}


结果:

MyStruct.i = 20
MyClass.i = 99


在这种情况下, MyStruct的值保持不变,因为它是按值传递给函数的。另一方面, MyClass的实例是通过引用传递的,这就是其值更改的原因。

关于c# - 为什么C#对象的行为一次类似于按值传递,而一次按引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19980318/

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