gpt4 book ai didi

c# - 将函数实现为 []

转载 作者:行者123 更新时间:2023-11-30 13:25:07 24 4
gpt4 key购买 nike

我有一个数组,它实际上是一个函数,但我想将它用作数组。我知道我可以写这些

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

但是我如何实现一个类似于数组的函数呢?我想做类似的事情

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

但是会出现编译错误

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)

最佳答案

在 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];

您可以通过适本地从类中删除 getter 或 setter 来将想法扩展为只读和只写属性。

关于c# - 将函数实现为 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1096238/

24 4 0
文章推荐: c# - 这些随机数是 'safe'
文章推荐: c# - 部署到 GAC
文章推荐: C# this.everything?
文章推荐: c# - 重用 switch 语句逻辑
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com