gpt4 book ai didi

ref - 带有 Ref Return 的 C# 索引器也支持集合

转载 作者:行者123 更新时间:2023-12-01 03:14:48 25 4
gpt4 key购买 nike

我在这里做错了什么,或者从 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?

最佳答案

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

关于ref - 带有 Ref Return 的 C# 索引器也支持集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49400277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com