实现[]的功能

3 c# arrays properties

我有一个真正的函数数组,但是我想将它用作数组.我知道我可以写这些

int var { get{return v2;} }
public int this[int v] { get { return realArray[v]; }
Run Code Online (Sandbox Code Playgroud)

但是我如何实现一个像数组一样的函数?我想做点什么

public int pal[int i] { get { return i*2; } }
Run Code Online (Sandbox Code Playgroud)

但是这会产生编译错误

error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's 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)
Run Code Online (Sandbox Code Playgroud)

Meh*_*ari 10

在C#中,声明参数化属性的唯一可能方法是索引器.但是,您可以通过创建一个提供索引器的类并向您的类添加该类型的属性来模拟类似的东西:

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];
Run Code Online (Sandbox Code Playgroud)

您可以根据需要从类中删除getter或setter,将该想法扩展为只读和只写属性.