gpt4 book ai didi

c# - 传递给未更新的类变量

转载 作者:行者123 更新时间:2023-12-04 10:35:05 25 4
gpt4 key购买 nike

这听起来应该是一个非常基本的问题,但我还没有找到答案(即使我知道肯定有很多),我想我的谷歌搜索技能很差,或者我不知道要搜索什么为了。

我有这个代码:

using System;

public class Program
{
public static void Main()
{
var service = new Service();

service.Execute();
}
}

public class Service
{
private int _foo;

public void Execute()
{
_foo = 1;

var bar = new Bar(_foo);

_foo = 2;

bar.WriteLine();
}
}

public class Bar
{
private readonly int _foo;

public Bar(int foo)
{
_foo = foo;
}

public void WriteLine()
{
Console.WriteLine(_foo);
}
}

我怎样才能让它打印 2 ? (基本上是 Bar之后的新值已经初始化了)

我尝试使用 ref但没有运气。

最佳答案

您尝试做的事情对 value type 没有意义

Value types and reference types are the two main categories of C# types. A variable of a value type contains an instance of the type. This differs from a variable of a reference type, which contains a reference to an instance of the type. By default, on assignment, passing an argument to a method, or returning a method result, variable values are copied. In the case of value-type variables, the corresponding type instances are copied.



通常,您会将其创建为属性并进行相应设置

给定
public class Bar 
{

public Bar(int foo) => Foo = foo;

public int Foo {get;set;}

public void WriteLine() => Console.WriteLine(Foo);

...

用法
public void Execute()
{

var bar = new Bar(1);

// set the property instead
bar.Foo = 2;

bar.WriteLine();

...

关于c# - 传递给未更新的类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60219017/

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