0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

同一のstatic変数(プロパティgetのみ経由でさえ)が違うオブジェクトを指し示す例

0
Last updated at Posted at 2020-01-28

実際の参照先とは

        static private char[] __TEST = null;
        static public char[] __TEST_GET
        {
            get
            {
                if (__TEST != null)
                    return __TEST;

                __TEST = new char[] { 'B', 'C', 'D' };
                return __TEST;
            }
        }
            char[] test_chars1 = Cfun.__TEST_GET;
            test_chars1[0] = 'R';
            char tc_1 = test_chars1[0];

            char[] test_chars2 = Cfun.__TEST_GET;
            char tc_2 = test_chars2[0];

このとき、
test_chars1はstatic private char[] __TESTの参照先(ア)
test_chars2もstatic private char[] __TESTの参照先(ア)
なので、tc_1もtc_2も'R'になります。
同じ参照先がtest_chars1[0] = 'R';で'R'に書き換えられてしまいます。

一方で、

        static private char[] __TEST = null;
        static public char[] __TEST_GET_B
        {
            get
            {
                /* ここだけコメントアウトします。
                if (__TEST != null)
                    return __TEST;
                */
                __TEST = new char[] { 'B', 'C', 'D' };
                return __TEST;
            }
        }

とすると、まるで動作が変わります。

test_chars1はstatic private char[] __TESTの参照先(カ)
とすると、
test_chars2はstatic private char[] __TESTの参照先(キ)
のようになります。
同じ【__TEST】を利用するのですが、newする都度、
(カ)を新規作成して返す、
(キ)を新規作成して返す、
という動作が.Netで行われます。

プロパティにGet{}しか実装していないのに、
同じ static private char[] __TEST なのに、
実際の参照先が異なる、というケースは普通にありえます。

実際は何を操作しているのか把握する必要がある

結局は、アセンブラのように実際は何を(どのオブジェクトを)操作しているのか、
意識して把握する必要があります。

このサンプルだけだと、書き方の問題というレベルですが、趣旨をわかって頂けると幸いです。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?