質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Visual Studio

Microsoft Visual StudioはMicrosoftによる統合開発環境(IDE)です。多種多様なプログラミング言語に対応しています。

Q&A

解決済

2回答

2088閲覧

コンストラクタの中での処理について

drer

総合スコア20

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Visual Studio

Microsoft Visual StudioはMicrosoftによる統合開発環境(IDE)です。多種多様なプログラミング言語に対応しています。

0グッド

0クリップ

投稿2016/11/18 16:23

c#

1namespace Csp 2{ 3 class Program 4 { 5 public static void Main(String[] args) 6 { 7 try 8 { 9 new A(100); 10 } 11 catch(Exception) 12 { 13 foreach (A d in A.obj) 14 { 15 Console.WriteLine(d.num); 16 } 17 } 18 } 19 } 20 21 class A 22 { 23 public static int i = 0; 24 public static ArrayList obj = new ArrayList(); 25 public int num; 26 public A(int num) 27 { 28 if (9 < A.i) throw new Exception(); 29 else 30 { 31 this.num = num; 32 obj.Add(this); 33 A.i++; 34 } 35 } 36 } 37}

thisを理解するためにこんなコードを書きました。
100が10個表示する予定で書いたのですが、なぜ何も表示されないのですか?
またthisは未初期化のインスタンスという認識でいいですか?

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

それが目的通りの挙動ならば、「例外処理」を「正常なロジック(反復処理の終了)」に使っているということになります。もちろん、プログラム自体に誤りはないのでしょうが、「エラー処理機能を使って反復を止める」というのはあまりお勧めできないですね。

投稿2016/11/18 17:24

HogeAnimalLover

総合スコア4830

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

自己解決

凡ミスしてたようです
これで動きました。

c#

1using System; 2using System.Collections; 3using System.Collections.Generic; 4using System.ComponentModel; 5using System.Linq; 6using System.Text; 7using System.Threading.Tasks; 8using System.Net; 9using System.Net.Sockets; 10 11namespace Csp 12{ 13 class Program 14 { 15 public static void Main(String[] args) 16 { 17 try 18 { 19 var p = new A(100); 20 } 21 catch(Exception) 22 { 23 foreach (A d in A.obj) 24 { 25 Console.WriteLine(d.num); 26 } 27 } 28 } 29 } 30 31 class A 32 { 33 public static int i = 0; 34 public static ArrayList obj = new ArrayList(); 35 public int num; 36 public A(int num) 37 { 38 while (true) 39 { 40 41 if (9 < A.i) throw new Exception(); 42 else 43 { 44 this.num = num; 45 obj.Add(this); 46 A.i++; 47 } 48 } 49 } 50 } 51}

投稿2016/11/18 16:56

drer

総合スコア20

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問