具有引用返回的C#索引器也支持集 [英] C# Indexers with Ref Return Gets that also Support Sets

查看:191
本文介绍了具有引用返回的C#索引器也支持集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里做错什么了吗?还是不支持从ref和allow set返回的C#7.2索引器?

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

作品:

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

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

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

推荐答案

正如@IvanStoev正确指出的那样,无需设置,因为该值是通过引用返回的.因此,索引器的调用者可以完全控制返回的值,因此可以为其分配新值,并且更改将反映在基础数据结构中(调用了索引器),因为该值是通过引用而不是通过引用返回的.值.

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.

这篇关于具有引用返回的C#索引器也支持集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆