我想创建一个只读索引器的索引器。提供一个具有任何数组类型属性的类,但我不知道如何将get访问器的值返回到循环,这里的主体是我想为此目的编译的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class arrys {
public int this[int index]
{
//get accessor
get
{
if (index >= 0 && index < 16)
//how i can return value from here
else
return -1;
}
//set accessor
/* set
{
}*/
}
}
class Program
{
static void Main(string[] args)
{
arrys a1 = new arrys();
for (int i = 0; i <= 20; i++)
{
int a = a1[i];
Console.WriteLine("a:" + a);
}
Console.ReadKey();
}
}
}
答案 0 :(得分:0)
首先你需要一个集合,所以你可以返回一些东西。
例如:
class arrys {
int[] _values;
public arrys(int size)
{
_values = new int[size];
}
public int this[int index]
{
if (index < _values.Length)
_values[index];
else
return -1;
}
}
// Usage
arrys a1 = new arrys(21);
for (int i = 0; i <= 20; i++)
{
int a = a1[i];
Console.WriteLine("a:" + a);
}
当然,这会将零写入控制台,因为您没有设置值。
答案 1 :(得分:-3)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class arrys {
public int this[int index]
{
//get accessor
get
{
if (index >= 0 && index < 16)
return index;
else
return -1;
}
//set accessor
/* set
{
}*/
}
}
class Program
{
static void Main(string[] args)
{
arrys a1 = new arrys();
for (int i = 0; i <= 20; i++)
{
int a = a1[i];
Console.WriteLine("a:" + a);
}
Console.ReadKey();
}
}
}