3

不変プロパティでインデクサー セット アクセサーを呼び出そうとするコードに対して、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# コンパイラは、想定どおりにケースを処理し、コードを正常にコンパイルします。

4

1 に答える 1