开发者

C# Making private instance variable accesable (jagged array)

In a attempt to put some more oop in a program i am looking to make a private instance variable in one class (object) accesable to a class.

private byte [][] J开发者_如何学编程;

All those code refers to this jagged array with this.

Now in the other class i putted all the for loops along with the consolewritlines to display the wanted results. Basicly it says "the name J does not exist in the current context"

But how exactly do i make this J accesable?

I have tried with get and set but i keep getting 'cannot convert to byte to byte[][]'

Also what kind of cyntax would i need with get and set?

Something along like this? Or would i need several more steps? :

public Byte JArray
get { return J; }  //can converrt to byte here
set { J = value; } //cannnot convert to byte here

Kind regards


If you want to expose a variable via a property, the type of the property has to be the same as the type of the variable (or compatible):

public byte[][] JArray
{
    get { return J; }
    set { J = value; }
}

However, you probably don't really need the setter - unless you actually want callers to be able to change J to refer to a different jagged array. Just with a getter they can still change values within the array, but they can't change the variable itself.

Even with this though, callers could still change the contents of the "outer" array, changing a whole "column" at a time:

foo.JArray[10] = new byte[10];

An alternative is to add an indexer to your class:

public byte this[int x, int y]
{
    get { return J[x][y]; }
    set { J[x][y] = value; }
}

This will only let callers access the actual elements, hiding the fact that it's backed by an array.

Exposing an array directly is generally a bad idea - indeed, leading minds consider arrays to be somewhat harmful.


If I understand the situation correctly, the problem is that your types are mismatched.

Since the variable's type is byte[][] (i.e., an array of arrays of bytes) your property's return type needs to be byte[][]. Currently it's Byte.


That's because the types of your private variable and the public property are not the same. Try this:

public byte[][] JArray
{
    get { return J; }
    set { J = value; }
}

Or even shorter using automatic properties:

public byte[][] JArray { get; set; }


if J is of type byte[][], the associate property should also be of type byte[][].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜