いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

C#の言語バージョンごとのデリゲートの書き方の変移 (delegate)


以下、メモ書きです。
言語のバージョン毎にデリゲートの書き方がどのように
変わったかをメモメモ。


v3.5になったからといって、v1.1のやり方が出来ないわけでは
ありません。


以下、サンプルです。

// vim:set ts=4 sw=4 et ws is nowrap ft=cs:
using System;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Runtime.Remoting;
using System.Threading;
using System.Windows.Forms;

namespace Gsf.Samples{

    public class SampleLauncher{

        static void Main(string[] args){

            string className = typeof(Dummy).Name;
            if(args.Length != 0){
                className = args[0];
            }

            if(!string.IsNullOrEmpty(className)){
                className = string.Format("{0}.{1}", typeof(SampleLauncher).Namespace, className);
            }

            Assembly     assembly = Assembly.GetExecutingAssembly();
            ObjectHandle handle   = Activator.CreateInstance(assembly.FullName, className);
            if(handle != null){
                object clazz = handle.Unwrap();

                if(clazz != null){
                    (clazz as IExecutable).Execute();
                }
            }
        }
    }

#region "共通インターフェース定義"
    interface IExecutable{
        void Execute();
    }
#endregion

#region "ダミークラス"
    class Dummy : IExecutable{

        public void Execute(){
            Console.WriteLine("THIS IS DUMMY CLASS.");
        }
    }
#endregion

#region "デリゲートのサンプル (.net framework 1.1)"
    class DelegateSample : IExecutable{

        public void Execute(){
            MethodInvoker methodInvoker = new MethodInvoker(DelegateMethod);
            methodInvoker();
        }

        private void DelegateMethod(){
            Console.WriteLine("SAMPLE_DELEGATE_METHOD.");
        }
    }
#endregion

#region "匿名デリゲートのサンプル (.net framework 2.0)"
    class AnonymousDelegateSample : IExecutable{

        delegate void SampleDelegate();

        public void Execute(){

            SampleDelegate d = delegate(){
                Console.WriteLine("SAMPLE_ANONYMOUS_DELEGATE.");
            };

            d.Invoke();
        }

    }
#endregion

#region "ラムダのサンプル (.net framework 3.5)"
    class LambdaSample : IExecutable{

        public void Execute(){

            MethodInvoker methodInvoker = () => {
                Console.WriteLine("SAMPLE_LAMBDA_METHOD.");
            };

            methodInvoker();

            Action action = () => {
                Console.WriteLine("SAMPLE_LAMBDA_METHOD_ACTION.");
            };

            action();

            Func sum = (x, y) => {
                return (x + y);
            };

            Console.WriteLine(sum(10, 20));

            Func sum2 = (int x, int y) => {
                return (x + y);
            };

            Console.WriteLine(sum2(10, 20));
        }
    }
#endregion
}