C#2.0

C#2.0の機能とサンプルをメモ代わりに貼る

/// C#2.0の新機能
/// (1) Generics
/// (2) 型制限
/// (3) Nullable Type
/// (4) Anonymous Method
/// (5) delegateの簡略表記
/// (6) Partial Type
/// (7) yield reurn, yield break

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

public interface ITest { }
public class Test : ITest
{
    // 以下を定義するためには、デフォルトコンストラクタも必要
    // public Test(int i) { }
}

public partial class Templ<T> : ITest where T : ITest, new()
{
    // これは、書けない。制限はシグネイチャではない
    // public void Func<U>(U u) where U : struct
    public void Func<U>(U u) where U : class
    {
        Console.WriteLine("Simple {0} {1}", typeof(T), typeof(U));
    }
}

public partial class Templ<T> : ITest where T : ITest, new()
{
    // whereからnew()などを取ることはできない
    public void Func<U>(Templ<U> u) where U : ITest, new()
    {
        Console.WriteLine("1 step {0} {1}", typeof(T), typeof(U));
    }
    public void Func<U>(Templ<Templ<U>> u) where U : ITest, new()
    {
        Console.WriteLine("2 step {0} {1}", typeof(T), typeof(U));
    }
}

public class MyList : IEnumerable
{
    private int[] ii;
    public MyList(int[] ii0) { ii = ii0; }
    public IEnumerator GetEnumerator()
    {
        foreach (int i in ii) yield return i;
    }
}
class CS20Test
{
    static void Main(string[] args)
    {
        Templ<Test> t = new Templ<Test>();
        Templ<Templ<Test>> s = new Templ<Templ<Test>>();
        t.Func("");  // Simple Test System.Int32
        t.Func(t);  // 1 step Test Test
        t.Func(s);  // 2 step Test Test

        int? ni = null;
        Console.WriteLine("Null [{0}]", ni+1);
        ni = 1;
        Console.WriteLine("Null [{0}]", ni+1);

        int k = 0;
        Action<int> a = delegate { Console.WriteLine("OK {0}", k); };
        int[] ii = {2,4,8};
        MyList ml = new MyList(ii);
        foreach (int i in ml) a(k = i);
    }
}