2D/3D array constructor

时间:2015-07-28 17:10:20

标签: c# arrays

I'd like to create a class called A which, during instantiation, give me 2D or 3D array of ints. If I call A(2) I should get object Arr[10,10] and when I call A(3) I should get Arr[10,10,10]. I don't care at this point what the elements are.

When I tried this:

class A
{
    public object Arr;
    public A(int dim)
    {
        switch (dim)
        {
            case 2:
                object Arr = new int[10, 10];
                break;
            case 3:
                object Arr = new int[10, 10, 10];
                break;
            default:
                object Arr = null;
                break;
        }
    }      
}

I got this:

CS0128 A local variable named 'Arr' is already defined in this scope.

When I tried this:

class A
{
    public object Arr;
    public A(2)
    {
        object Arr = new int[10, 10];
    }
    public A(3)
    {
        object Arr = new int[10, 10, 10];
    } 
}

I got this:

CS1001 Identifier expected

I'm short of ideas now.

Can I do this at all?

2 个答案:

答案 0 :(得分:3)

You get this:

CS0128 A local variable named 'Arr' is already defined in this scope.

Because you are defining again object Arr inside each case. It should just be Arr = new int[10, 10, 10];

In the second example in which you get this:

CS1001 Identifier expected

My guess is what you really want is to instantiate the public Arr attribute of the class A. So you probably want something like this:

this.Arr = new int[10, 10];

Inside each constructor.

More about this CS1001 Identifier expected. It is because the signature of the method is expecting a variable, and you are passing 2 and 3, and I guess what you want there is int n?

答案 1 :(得分:1)

您的第二个示例不正确,因为您不需要两个Constructor。您只需要一个Constructor,只需使用Switch-Case这样的内容(不要在每个案例中再次定义Arr):

public class A
{
    public object Arr;
    public A(int dim)
    {
        switch (dim)
        {
            case 2:
                 Arr = new int[10, 10];
                break;
            case 3:
                 Arr = new int[10, 10, 10];
                break;
            default:
                 Arr = null;
                break;
        }
    }
}

然后:

A obj1 = new A(2);
var x = obj1.Arr;//int[10,10]
A obj2 = new A(3);
var y = obj2.Arr;//int[10,10,10]