为什么 C# 编译器会为尝试在不可变属性上调用索引器集访问器的代码生成错误 CS1612?
using System;
using System.Collections.Generic;
using System.Text;
namespace StructIndexerSetter
{
struct IndexerImpl {
private TestClass parent;
public IndexerImpl(TestClass parent)
{
this.parent = parent;
}
public int this[int index]
{
get {
return parent.GetValue(index);
}
set {
parent.SetValue(index, value);
}
}
}
class TestClass
{
public IndexerImpl Item
{
get
{
return new IndexerImpl(this);
}
}
internal int GetValue(int index)
{
Console.WriteLine("GetValue({0})", index);
return index;
}
internal void SetValue(int index, int value)
{
Console.WriteLine("SetValue({0}, {1})", index, value);
}
}
class Program
{
static void Main(string[] args)
{
var testObj = new TestClass();
var v = testObj.Item[0];
// this workaround works as intended, ultimately calling "SetValue" on the testObj
var indexer = testObj.Item;
indexer[0] = 1;
// this produced the compiler error
// error CS1612: Cannot modify the return value of 'StructIndexerSetter.TestClass.Item' because it is not a variable
// note that this would not modify the value of the returned IndexerImpl instance, but call custom indexer set accessor instead
testObj.Item[0] = 1;
}
}
}
根据文档,此错误意味着以下内容:“尝试修改作为中间表达式的结果生成但未存储在变量中的值类型。当您尝试直接修改通用集合中的结构,如下例所示:"
在这种情况下不应该产生错误,因为表达式的实际值没有被修改。注意:Mono C# 编译器按预期处理这种情况,成功编译代码。