C# Indexers with Ref Return Gets that also Support Sets

戏子无情 提交于 2019-12-23 12:45:03

问题


Am I doing something wrong here, or as of C# 7.2 Indexers that return by ref and allow set are not supported?

Works:

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

Works too:

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

Fails:

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

Fails too:

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

So, is there no way to have a ref return yet allow the indexer also support Set?


回答1:


As @IvanStoev correctly pointed out, there is no need for set, since the value is returned by reference. Therefore the caller of the indexer has complete control over the returned value and can therefore can assign it a new value, with the changes being reflected in the underlying data structure (whose indexer was being called) since the value was returned by reference and not by value.



来源:https://stackoverflow.com/questions/49400277/c-sharp-indexers-with-ref-return-gets-that-also-support-sets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!