langsmith:222
From: Hiroshi Yuki <hyuki hyuki.com>
Date: Sun, 17 Apr 2005 14:46:03 +0900
Subject: [langsmith:222] Re: C#の匿名メソッド..なぜ、ローカル変数を共有するのか?
結城です。 On Sat, 16 Apr 2005 00:32:04 -1000 (HST) Shiro Kawai <shiro lava.net> wrote: > C#は両方のいいとこ取りを狙ったんでしょうが、それはそれとして、 > ローカルな状態を全てオブジェクトを基礎に説明する言語があっても > おもしろいかなあとは思います。つまりローカル変数なんてものはない、 > 全てはインスタンス変数なのだ、みたいな。 (Java的に考えると) メソッド内のローカル変数というのは、オブジェクトの持ち物というよりも、 そのメソッドを実行したスレッド(実行主体)の持ち物という気がします。 もしも「すべてはインスタンス変数」として実現できるなら、 オブジェクトとスレッドが密に結びつくことになるかもしれませんね。 それはそれとして、元のC#のコードをJavaで書いてみました。 interface D { void d(); } class MutableInt { public int value; public MutableInt(int value) { this.value = value; } } class Test { static D[] F() { D[] result = new D[3]; final MutableInt x = new MutableInt(0); for (int i = 0; i < 3; i++) { final MutableInt y = new MutableInt(0); result[i] = new D() { public void d() { x.value++; y.value++; System.out.println(x.value + " " + y.value); } }; } return result; } public static void main(String[] args) { D[] d = F(); for (int i = 0; i < d.length; i++) { d[i].d(); } for (int i = 0; i < d.length; i++) { d[i].d(); } } } /* 実行結果 1 1 2 1 3 1 4 2 5 2 6 2 */ ---- 結城浩 http://www.hyuki.com/ http://www.textfile.org/ In the beginning God created the heaven and the earth. (Genesis 1:1) -- ML: langsmith quickml.atdot.net 使い方: http://www.atdot.net/~ko1/quickml
197 2005-04-15 09:56 [t.machida.unicom jco] C#の匿名メソッド..なぜ、ローカル変数を共有するのか? 198 2005-04-15 11:15 ┣[shiro lava.net ] 201 2005-04-15 12:02 ┃┣[t.machida.unicom jco] 202 2005-04-15 12:16 ┃┗[maeda-langsmith atus] 199 2005-04-15 11:32 ┗[maeda-langsmith atus] 200 2005-04-15 11:50 ┣[maeda-langsmith atus] 203 2005-04-15 12:27 ┗[t.machida.unicom jco] 204 2005-04-15 12:52 ┣[matz ruby-lang.org ] 209 2005-04-16 14:26 ┗[maeda-langsmith atus] 210 2005-04-16 15:41 ┗[t.machida.unicom jco] 211 2005-04-16 15:47 ┣[t.machida.unicom jco] 212 2005-04-16 16:13 ┗[matz ruby-lang.org ] 213 2005-04-16 16:31 ┣[maeda-langsmith atus] 215 2005-04-16 16:54 ┃┗[matz ruby-lang.org ] 214 2005-04-16 16:35 ┗[t.machida.unicom jco] 216 2005-04-16 16:59 ┣[matz ruby-lang.org ] 217 2005-04-16 17:34 ┃┗[t.machida.unicom jco] 219 2005-04-16 18:20 ┃ ┣[kmori lsi-j.co.jp ] 220 2005-04-16 19:32 ┃ ┗[shiro lava.net ] 221 2005-04-17 00:16 ┃ ┣[matz ruby-lang.org ] -> 222 2005-04-17 14:46 ┃ ┗[hyuki hyuki.com ] 223 2005-04-18 00:30 ┃ ┗[matz ruby-lang.org ] 218 2005-04-16 17:43 ┗[maeda-langsmith atus]