C# 入門 & 実践 / C sharp

4-7. [ ジェネリック/コレクション ] 1. ジェネリックの基本


ジェネリッククラス


    public class Generic<T>
    {
        public T Field;
    }
    
    class Tester
    {
        static void Main()
        {
            Generic<string> gs = new Generic<string>();
            gs.Field = "文字列になりました!";
            Generic<int> gi = new Generic<int>();
            gi.Field = 100;
        }
    }

これがジェネリック型です!
<T> がポイントというか
オブジェクト生成の <string> によって T の部分は string となります。
<int> とすると int として利用できるということです。

ジェネリック型を利用することによって、キャストやボックス化の必要は無く
特定の型で利用できるため、従来のコレクションとは違い、サイズも小さく、速度も速いそうです。

ジェネリックメソッド


ジェネリックメソッドは、ジェネリック型でも非ジェネリック型の中でも書けます。

public T getG<T>(T arg)
というメソッドをジェネリッククラスとそうでないクラスに作ってみました。

    public class Generic<T>
    {
        public T Field;
        public T getG<T>(T arg)
        {
            return arg;
        }
    }
    public class NotGeneric
    {
        public T getG<T>(T arg)
        {
            return arg;
        }
    }

    class Tester
    {
        static void Main()
        {
            Generic<string> gs = new Generic<string>();
            string gs_str = gs.getG<string>("Generic");
            NotGeneric ngs = new NotGeneric();
            string ngs_str = ngs.getG<string>("Not Generic");

            Console.WriteLine("{0} / {1}" , gs_str, ngs_str);
        }
    }

System.Collections.Generics名前空間


abstract class Comparer<T>
abstract class EqualityComparer<T>
class Dictionary<TKey, TValue>
class LinkedList<T>
class List<T>
class Queue<T>
class SortedDictionary<TKey, TValue>
class SortedList<TKey, TValue>
class Stack<T>
struct KeyValuePair<TKey, TValue>
interface ICollection<T>
interface IComparer<T>
interface IDictionary<TKey, TValue>
interface IEnumerable<T>
interface IEnumerator<T>
interface IEqualityComparer<T>
interface IList<T>

さて、次はインターフェイスの実装やList,Queue,Stack,Dictionary などの利用を見て行きたいと思います。





4-6. インデクサ / indexer « 4. C# 入門 Level 2 » 4-8. [ ジェネリック/コレクション ] 2. インターフェイスの実装 / IEnumerable で foreach を実装


C# 入門 & 実践 / C sharp