我开始在c#中解析主题索引器,并在运行测试任务时遇到问题:
Index.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];
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Program.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();
}
Run Code Online (Sandbox Code Playgroud)
正如你在调用indexer1后看到的那样,我希望数组值更改为2和3,然后我得到3.3(我知道这是因为当我调用indexer0时我将值更改为2.3,然后我使用数组2,3,3,4,我可以通过将值写入临时变量来修复此问题,但后来我无法将值从indexer2复制到indexer3(所需值为25.)请帮助我处理其中两个问题.
您的实现的问题是您没有复制原始数组.这将创建对同一数组的第二个引用
arr = arr1;
Run Code Online (Sandbox Code Playgroud)
如此修改循环内部,
arr[i] = arr1[i + 1];
Run Code Online (Sandbox Code Playgroud)
正在四处移动并覆盖原始数组的元素.
通过分配一个新数组并将原始数组的内容复制到其中来解决此问题:
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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,您Index将拥有原始数组的副本.如果你想要一个"窗口"到原来的数组,而不是一个副本(即有变化Main的array是通过看得见index1,index2等店arr不变,并存储初始指数在私有变量.现在可以更改索引执行做"索引翻译",即减去存储x的index来获得正确的索引:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |