gpt4 book ai didi

c# - 将变量绑定(bind)到列表

转载 作者:行者123 更新时间:2023-11-30 21:47:57 25 4
gpt4 key购买 nike

我有一个非常简单的层次结构:1 个接口(interface)由几个类继承,看起来与此类似但缺少一些属性:

public interface Test
{
List<double> Numbers { get; set; }
double Result { get; set; }
}

public class A : Test
{
public List<double> Numbers { get; set; } = new List<double>();
public double Result { get; set; }
}

public class B : Test
{
public List<double> Numbers { get; set; } = new List<double>();
public double Result { get; set; }
}

这是我要实现的示例代码:

        A a = new A();
B b = new B();
a.Numbers.Add(b.Result);
Console.WriteLine(a.Numbers.Last());
b.Result = 50;
Console.WriteLine(a.Numbers.Last());

输出

0

0

问题是在第 5 行,我正在更改 b.Result 的值,但我想在包含b.Result 的先前状态,我该怎么做?

最佳答案

double 是一个值类型,无论何时传递它,都会创建它的一个副本。它不是通过引用传递的,所以当你说 a.Numbers.Add(b.Result); 你实际上是在创建 b.Result 的副本并传递给添加 方法。

你可以阅读这个 Article通过示例来理解这个概念。

来自 C# 规范:

⦁ Types and variables

There are two kinds of types in C#: value types and reference types. Variables of value types directly contain their data whereas variables of reference types store references to their data, the latter being known as objects. With reference types, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable. With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other (except in the case of ref and out parameter variables).

这是一个解决方法,无论如何都不推荐:

public interface Test
{
List<DoubleByRef> Numbers { get; set; }
DoubleByRef Result { get; set; }
}

public class A : Test
{
public List<DoubleByRef> Numbers { get; set; } = new List<DoubleByRef>();
public DoubleByRef Result { get; set; } = new DoubleByRef(0);
}

public class B : Test
{
public List<DoubleByRef> Numbers { get; set; } = new List<DoubleByRef>();
public DoubleByRef Result { get; set; } = new DoubleByRef(0);
}

public class DoubleByRef
{
public double Value { set; get; }
public DoubleByRef(double d)
{
Value = d;
}

public override string ToString()
{
return Value.ToString();
}
}

用法:

A a = new A();
B b = new B();
a.Numbers.Add(b.Result);
Console.WriteLine(a.Numbers.Last());
b.Result.Value = 50;
Console.WriteLine(a.Numbers.Last());

打印:

0
50

关于c# - 将变量绑定(bind)到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38029966/

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