基本上我正在尝试实现自己的数组类,我想知道创建一个生成未知数量的私有实例变量的公共方法是否可行?类似的东西:
public class myArray {
public myArray(int length) {
for(int i = 0; i < length; i++) {
int component+i;
}
}
int component(int indexOfComponent) {
return component+indexOfComponent;
}
}
我知道for循环中的代码行是没有意义的。但我只是想我会说明我在说什么。使用3作为构造函数参数从myArray类创建对象会产生什么结果:
public class myArray {
private int component1;
private int component2;
private int component3;
public myArray(int length) {
for(int i = 0; i < length; i++) {
int component+i;
}
int component(int indexOfComponent) {
return component+indexOfComponent;
}
}
}
我知道这些变量只存在于for循环中,但这是我能够举例说明我想要做的最好的方法。如果我试图实现自己的数组类,这甚至是可行的方法吗? 也;还有一件事我认为可能值得单独提出一个问题,但这是用for循环动态命名变量的整个问题。
答案 0 :(得分:1)
基本上我正在尝试实现自己的数组类
我敦促你不要这样做。
我想知道创建一个生成未知数量的私有实例变量的公共方法是否可行
没有。变量需要在编译时中知道。
“要走的路”是使用数组或其他现有的集合类型。
从根本上说,不能直接在C#中实现数组。数组和字符串是实例大小因对象而异的唯一对象。对于其他所有内容,每个对象的布局都是相同的。
(如评论中所述,您可以使用Reflection.Emit
或类似的东西为每个实例动态创建新类型,但您确实确实不希望这样做。)< / p>