简体   繁体   中英

How to get current array index in property

Hi i am having two classes as below. in our application we will not store data in the array we will be storing in a separate big string and we will be reading from there but while setting and getting the value to array i need the index so that i can take sub string using the index.

public class ClassA
{
    private ClassB[] _classB;
    publc ClassB[] classB
    {
      get
      {
          return _classB;
      }
      set
      {
          _classB=value;
      }
  }

}

public class ClassB
{
  public int x;
}

if i set any value to classB like

 classA.classB[10].x=1;

is there any way i can get the current index being set in the set property like 10 as the current index or do i need to use Indexes please help me.

Why not make the property declaration read only (just a "get"), and add a Set method:

public void SetValue( int idx, ClassB value )
   {
   classB[idx] = value;
   }

Of course there are no precondition checks and no exception handling code in my example, but if you need to know the index in the set method, I'd go with something like this.

Why do you want to wrap a simple int in a class?

And why expose a fixed-length array publicly? Why not use an ArrayList or one of the other collections that are built in to in the .NET library?

You cannot get the index while setting the property, if for no other reason than that you aren't setting a property in your example at all. You are getting a property value (the classB array), and then setting the x field of the object in that array's position.

There are alternative syntaxes which might work for you. It depends on what your requirements are. Unfortunately, your question doesn't show how you will use the index, so it's not possible to know what you really need.

One option is to just make a method that does the work:

class ClassA
{
    public void SetItemXAt(int index, int value)
    {
        classB[index].x = value;
    }
}

Then you have the index parameter to do with what you want.

A variation on this theme is to implement an indexer property on the type:

class ClassA
{
    public int this[int index]
    {
        get { return classB[index].x; }
        set { classB[index].x = value; }
    }
}

Again, the index parameter is available to you here to use as you wish.

If neither of the above help, you need to fix the question so that you're clear about what you actually want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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