裏口からのC#実践入門

シーン 2 ライブラリの問題

2.1 旧世代のコレクションを使う

C# で何かやったことはないので、Hashtableの存在知らなかった。
System.Collections 名前空間は使わず、System.Collections.Generic を使うこと。

using System;
using System.Collections;
using System.Collections.Generic;

namespace Uraguchi.Scene2
{
    public class Tenshi1
    {
        public static void Run1()
        {
            var coll = new Dictionary<object, object>();

            try
            {
                Console.WriteLine(coll["a"]);
            }
            catch(Exception)
            {
                Console.WriteLine("Hashtableと互換性がありません");
            }
        }

        public static void Run2()
        {
            var coll = new Hashtable();
            Console.WriteLine(coll["a"]);
        }
    }
}

2-2 コレクションを返す

Enumerable では ForEach が使えないのかぁ。Count もプロパティじゃなくてメソッド
Enumerable クラス (System.Linq)

  • アクマくん
using System;
using System.Linq;
using System.Collections.Generic;

namespace Uraguchi.Scene2
{
    public class Akuma2
    {
        private static List<int> SearchItems(Func<int, bool> checkCondition)
        {
            int[] array = { 1, 2, 3 };
            var list = new List<int>();
            foreach(var item in array)
            {
                if (checkCondition(item))
                    list.Add(item);
            }

            return list;
        }

        public static void Run()
        {
            var r = SearchItems(n => n >= 1);
            r.RemoveAt(1);
            Console.WriteLine("結果は {0} 個です。", r.Count);
            r.ForEach(Console.WriteLine);
        }
    }
}
  • テンシちゃん
using System;
using System.Linq;
using System.Collections.Generic;

namespace Uraguchi
{
    public class Tenshi2
    {
        private static IEnumerable<int> SearchItems(Func<int, bool> checkCondition)
        {
            int[] array = { 1, 2, 3 };
            var list = new List<int>();
            foreach(var item in array)
            {
                if (checkCondition(item))
                    list.Add(item);
            }

            return list;
        }

        public static void Run()
        {
            var r = SearchItems(n => n >= 2);
            // r.RemoveAt(1); // コンパイルエラー
            Console.WriteLine("結果は {0} 個です。", r.Count());
            foreach(var item in r)
                Console.WriteLine(item);
        }
    }
}