【问题标题】:How implement an array property that does not simply encapsulate a field?如何实现不简单封装字段的数组属性?
【发布时间】:2013-04-02 00:54:33
【问题描述】:

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

根据this 文章,以下应该可以工作:

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# 中搜索索引器

标签: c# arrays properties


【解决方案1】:

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;}
}

【讨论】:

  • 显式实现接口的好主意!
  • @DanielHilgarth 我几乎想知道它是否应该是IIndexer<int,double>。
  • 如果一个类中有多个具有相同类型的命名索引器,那将是有问题的。如果嵌套类型确实只存在于实现命名索引器,则另一种选择是使用嵌套类型。
  • @DanielHilgarth 确实 - 仅包含对“外部”对象的引用的 struct 可能是一个非常有效的选择。
  • 好主意。我认为这实际上是最好的解决方案,如果 - 再次 - 这些类型只存在于实现命名索引器。如果这些类型除了索引器之外还有任何其他公共方法或属性,它们应该是普通的公共类。
【解决方案2】:

方法必须是这样的:

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

【讨论】:

    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多