C#里:
public class A
{
int[] nodes = new int[] { };
public int this[int index]
{
get
{
return nodes[index];
}
set
{
nodes[index] = value;
}
}
} class B : A
{
//..... //这里要访问父类A里的nodes.Length,该怎么做? A里的nodes只能是私有的,不可以改了。有其他办法么? //可以通过A类里那个this[]属性来访问到nodes的长度么? 怎么写? 谢谢
}
public class A
{
int[] nodes = new int[] { };
public int this[int index]
{
get
{
return nodes[index];
}
set
{
nodes[index] = value;
}
}
} class B : A
{
//..... //这里要访问父类A里的nodes.Length,该怎么做? A里的nodes只能是私有的,不可以改了。有其他办法么? //可以通过A类里那个this[]属性来访问到nodes的长度么? 怎么写? 谢谢
}
如
public int Length{get{return nodes.Length;}}
要想办法通过this[]哪个属性访问
//可以通过A类里那个this[]属性来访问到nodes的长度么? 怎么写? 谢谢那就把 A 里 nodes 的 private 改为 protected,这样在 B 中可以访问 base.nodes.Length,
但外部无法访问到 nodes!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApp
{
public class A
{
int[] nodes = new int[] { };
public int this[int index]
{
get
{
return nodes[index];
}
set
{
nodes[index] = value;
}
} public A(int length)
{
nodes = new int[length];
}
} class B : A
{
public int NodeLength
{
get
{
int length = 0;
int value;
try
{
for (; ; length++)
{
value = base[length];
}
}
catch { } return length;
}
} public B(int length) : base(length) { }
} class Program
{
static void Main(string[] args)
{
B b = new B(5);
b[0] = 1;
b[1] = 2; Console.WriteLine(b.NodeLength);
Console.ReadLine();
}
}
}
A test = new A();
bool IsError = false;
int length = 0;
while(!IsError)
try
{
int n = test[3];
}
catch (Exception e)
{
IsError = true;
length = length + 1;
}
Console.WriteLine(length);//这个就是你要的length
Console.ReadLine();
这么写是空数组!!!
Console.WriteLine(nodes.Length);
A test = new A();
bool IsError = false;
int length = 0;
while(!IsError)
try
{
length = length + 1;
int n = test[length];
}
catch (Exception e)
{
IsError = true;
length = length - 1;
}
Console.WriteLine(length);
Console.ReadLine();当然,上面哥们说的是,
int[] nodes = new int[] { };这么写是空数组!!!