如何实现不简单封装字段的数组属性

本文关键字:字段 封装 数组 属性 不简单 何实现 实现 | 更新日期: 2023-09-27 18:08:38

我想实现一个属性,它根据接收到的索引返回一个值。我是而不是,只是封装了一个私有数组。实际上,我将返回的数据不存储在任何数组中,而是存储在成员对象中。这个array属性只是一种以索引方式访问数据的方式,而不需要以索引方式存储数据。

根据这篇文章,以下内容应该起作用:

public double Angles[int i] 
{
    get { // return a value based on i; }
}
然而,我得到以下错误:
The type or namespace 'i' could not be found (are you missing a using directive or an assembly reference?)
Invalid token ']' in class, struct or interface member declaration
Invalid expression term 'int'
Bad array declarator: To declarate 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.
Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

从这些错误中,我认为编译器似乎认为我试图创建一个数组成员。很明显我的语法是错误的。有人能告诉我正确的做法吗?

如何实现不简单封装字段的数组属性

命名索引器在c#中不存在。但是,您可以将Angles添加为具有索引器的某种类型的对象,即

public class Foo {
    public Angles Angles { get { return angles; } }
    ...
}
...
public class Angles {
    public double this[int index] { get { ... } }
    ...
}

或者如果你想在一个类中实现:

public class Foo : IAngles {
    public IAngles Angles { get { return this; } }
    double IAngles.this[int index] { get { ... } }
}
public interface IAngles {
    double this[int index] { get;}
}

方法必须是这样的:

public double this[int i] 
{
    get { // return a value based on i; }
}