gpt4 book ai didi

c# - C# 中的索引与内存一起使用

转载 作者:行者123 更新时间:2023-11-30 14:46:38 25 4
gpt4 key购买 nike

我开始在c#中解析主题索引器,在运行测试任务时遇到了一个问题:

索引.cs:

class Index
{
double[] arr;
public int Length
{
get;
set;
}
public double this[int x]
{
get { return arr[x]; }
set
{
arr[x] = value;
}
}
public Index(double[] arr1, int x, int y)
{
Length = y;

arr = arr1;

for (int i = x; i <= y; i++)
{
if (i == 0)
{
arr[i] = arr1[i + 1];
}
else
{
arr[i - 1] = arr1[i];
}
}
}
}

程序.cs

static void Main(string[] args)
{
double[] array = { 1, 2, 3, 4 };
var indexer0 = new Index(array, 1, 2);
Console.WriteLine(indexer0.Length);
Console.WriteLine("Result = 2,3");
var indexer1 = new Index(array, 1, 2);
Console.WriteLine(indexer1[0]);
Console.WriteLine(indexer1[1]);
Console.WriteLine("Copy 25");
var indexer2 = new Index(array, 1, 2);
var indexer3 = new Index(array, 0, 2);
indexer2[0] = 25;
Console.WriteLine(indexer3[1]);
Console.WriteLine("Array");
foreach(var item in array)
{
Console.WriteLine(item);
}

Console.ReadKey();
}

正如您在调用 indexer1 后看到的,我希望数组值更改为 2 和 3,我得到 3.3(我理解这是因为当我调用 indexer0 时我更改了值到 2.3,然后我使用数组 2、3、3、4,我可以通过将值写入临时变量来解决这个问题,但是我无法将值从 indexer2 复制到 indexer3(所需值为 25。 ) 请帮我解决其中两个问题。

最佳答案

您的实现的问题是您没有制作原始数组的副本。这将创建对同一数组的第二个引用

 arr = arr1;

所以循环内的修改,就像这个,

arr[i] = arr1[i + 1];

四处移动并覆盖原始数组的元素。

通过分配一个新数组并将原始数组的内容复制到其中来解决此问题:

public int Length { get { return arr.Length; } }
public Index(double[] arr1, int x, int y) {
arr = new double[y];
Array.Copy(arr1, x, arr, 0, y);
}

请注意,您的索引 将具有原始数组的副本。如果您想要原始数组的“窗口”,而不是副本(即,通过 index1 可以看到对 Mainarray 的更改, index2 等存储 arr 不变,并将初始索引存储在私有(private)变量中。您现在可以更改索引器实现以进行“索引翻译”,即减去从 index 中存储 x 以获得正确的索引:

class Index {
private readonly double[] arr;
private readonly int offset; // set this to x in the constructor
public int Length { get { return arr.Length; } }
public double this[int idx] {
get { return arr[idx+offset]; }
set { arr[idx+offset] = value; }
}
public Index(double[] arr1, int x, int y) {
arr = arr1;
offset = x;
}
}

Demo.

关于c# - C# 中的索引与内存一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48367235/

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