【问题标题】:C# Indexers with Ref Return Gets that also Support Sets具有 Ref Return Gets 的 C# 索引器也支持 Set
【发布时间】:2018-08-30 05:10:21
【问题描述】:

我在这里做错了什么,还是从 C# 7.2 开始不支持通过 ref 返回并允许设置的索引器?

作品:

public ref byte this[int index] {
  get {
      return ref bytes[index];
  }
}

也可以:

public byte this[int index] {
  get {
      return bytes[index];
  }
  set {
    bytes[index] = value;
  }
}

失败:

public ref byte this[int index] {
  get {
      return ref bytes[index];
  }
  set { //<-- CS8147 Properties which return by reference cannot have set accessors
    bytes[index] = value;
  }
}

也失败了:

public ref byte this[int index] {
  get {
      return ref bytes[index];
  }
}

public byte this[int index] { //<-- CS0111 Type already defines a member called 'this' with the same parameter types
  set {
    bytes[index] = value;
  }
}

那么,有没有办法让 ref 返回但允许索引器也支持 Set?

【问题讨论】:

  • 我猜你明白public ref byte this[int index] 允许get set 操作。类似于公共字段。
  • @IvanStoev 是的。但显然我不能同时拥有 Get 和 Set(如果使用 ref)。这就是我最初想做的事情。
  • 从我之前的评论中应该很明显。一旦我从您的索引器获得ref byte,我就可以为其分配一个值,并且不会涉及任何设置器(因为我基本上有一个指向您的基础数据缓冲区的指针)。因此,拥有一个 setter 没有任何意义。
  • @IvanStoev 哦,是的,你是对的!我真傻!然后,您应该将其发布为我很乐意接受的答案!谢谢。

标签: ref indexer c#-7.2


【解决方案1】:

正如@IvanStoev 正确指出的那样,不需要设置,因为该值是通过引用返回的。因此,索引器的调用者可以完全控制返回的值,因此可以为其分配一个新值,因为该值是通过引用而不是通过引用返回的,因此更改会反映在底层数据结构(其索引器被调用)中价值。

【讨论】:

    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 2010-09-14
    • 2012-09-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    相关资源
    最近更新 更多