10
10

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.

OfTypeの使い方

Posted at

WindowsのFormの画面にCheckBoxがたくさんあるとします。
プログラムで、すべてチェック済みにしたいとき、

C#
foreach (var cntr in Controls)
{
	var cb = cntr as CheckBox;
	if (cb != null) cb.Checked = true;
}

このように書くと思いますが、OfTypeを使うと以下のようにかけます。

C#
foreach (var cb in Controls.OfType<CheckBox>()) cb.Checked = true;

似たようなものに Castがありますが、Castでは、型が異なると例外になります。

10
10
0

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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?