Implement the function as []

I have an array that really is a function, however I would like to use it as an array. I know that I can write these

int var { get{return v2;} }
public int this[int v] { get { return realArray[v]; }

but how to implement a function like an array? I would like to do something like

public int pal[int i] { get { return i*2; } }

But this will lead to a compilation error

error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.
error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
+3
source share
5 answers

In C #, the only possible way to declare a parameterized property is through an index. However, you could mimic something like this by creating a class that provides an index and adds a property of this type to your class:

class ParameterizedProperty<TProperty, TIndex> {
     private Func<TIndex, TProperty> getter;
     private Action<TIndex, TProperty> setter;
     public ParameterizedProperty(Func<TIndex, TProperty> getter,
                                  Action<TIndex, TProperty> setter) {
        this.getter = getter;
        this.setter = setter;
     }
     public TProperty this[TIndex index] {
        get { return getter(index); }
        set { setter(index, value); }
     }   
}

class MyType {
    public MyType() {
        Prop = new ParameterizedProperty<string, int>(getProp, setProp);
    }
    public ParameterizedProperty<string, int> Prop { get; private set; }
    private string getProp(int index) {
        // return the stuff
    }
    private void setProp(int index, string value) {
        // set the stuff
    }
}

MyType test = new MyType();
test.Prop[0] = "Hello";
string x = test.Prop[0];

You can expand the read-only idea and write only properties by removing the getter or setter from the class, if necessary.

+10

, , :

public int this[int i] { get { return i * 2; } }

, pal:

public class Wrapper
{
    public int this[int i] { get { return i * 2; } }
}

...

public Wrapper pal { get { return _someWrapperInstance; } }

pal[ix], pal[3] ..

+1

:

public int[] pal { get { return realArray; } }

:

public class ActingAsArray {
   private int[] _arr;
   public ActingAsArray(int[] arr) { _arr = arr; }
   public int this[int v] { get { return _arr[v]; } }
}

public ActingAsArray pal { get { return new ActingAsArray(realArray); } }
+1

( ) #. , , indexer, . this . , , , .

+1

If you don't mind using a bit of VB.Net, it supports parameterized properties (it still beats me why this is not possible in C #, since .Net is obviously capable of doing this)

This way you can create your own class in VB.Net and just reference the VB.Net DLL in your project.

This can, of course, be somewhat annoying if your class changes frequently: - /

0
source

Source: https://habr.com/ru/post/1712061/


All Articles