我在这里做错了什么,或者从 C# 7.2 开始,不支持通过 ref 返回和允许设置的索引器?
Works:
public ref byte this[int index] {
get {
return ref bytes[index];
}
}
也有效:
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;
}
}
也失败:
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 正确指出的那样,不需要设置,因为该值是通过引用返回的。因此,索引器的调用者可以完全控制返回的值,因此可以为其分配一个新值,并且更改反映在底层数据结构(其索引器被调用)中,因为该值是通过引用返回的,而不是通过价值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)