简体   繁体   English

是否可以在 C# 中创建一个公共方法来生成未知数量的私有实例变量?

[英]is it possible to create a public method that generates an unknown number of private instance variables in C#?

Basically I am trying to implement my own array class, and I was wondering if creating a public method that generates an unknown number of private instance variables was the way to go?基本上我正在尝试实现我自己的数组类,我想知道是否创建一个生成未知数量的私有实例变量的公共方法是要走的路? Something like:就像是:

public class myArray {
    public myArray(int length) {
        for(int i = 0; i < length; i++) {
            int component+i;
        }
    }
    int component(int indexOfComponent) {
        return component+indexOfComponent; 
    }
}

I know the the line of code inside that for loop makes no sense.我知道 for 循环中的代码行没有意义。 But I just thought I would illustrate what I was talking about.但我只是想我会说明我在说什么。 What would result from creating an object from the myArray class with 3 as the constructor parameter would be:从 myArray 类以 3 作为构造函数参数创建对象的结果是:

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; 
        }
    }
}

And I know those variables would only exist inside the for loop, but that is the best way I can exemplify what I am trying to do.而且我知道这些变量只会存在于 for 循环中,但这是我可以举例说明我正在尝试做的事情的最佳方式。 Is this even the way to go if I am trying to implement my own array class?如果我试图实现我自己的数组类,这甚至是要走的路吗? Also;还; there's one more thing about this that I think may deserve a separate question but it's the whole problem with naming variables dynamically with a for loop.关于此还有一件事我认为可能值得单独提出一个问题,但这是使用 for 循环动态命名变量的整个问题。

Basically I am trying to implement my own array class基本上我正在尝试实现我自己的数组类

I'd urge you not to do that.我劝你不要那样做。

I was wondering if creating a public method that generates an unknown number of private instance variables was the way to go我想知道是否创建一个生成未知数量的私有实例变量的公共方法是要走的路

No. The variables need to known at compile-time .不。变量需要在编译时知道。

The "way to go" is to use an array or another existing collection type. “要走的路”是使用数组或其他现有的集合类型。

Fundamentally you can't implement arrays directly in C#.从根本上说,您不能直接在 C# 中实现数组。 Arrays and strings are the only objects where the size of an instance varies from object to object.数组和字符串是唯一实例大小因对象而异的对象。 For everything else, the layout is the same for every object.对于其他所有内容,每个对象的布局都是相同的。

(As mentioned in comments, you could dynamically create a new type for each instance using Reflection.Emit or something similar, but you really really don't want to do that.) (正如在评论中提到,你可以动态地创建使用每个实例的新型Reflection.Emit或类似的东西,但你真的真的不想这样做。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM