일반 자유 패턴

안녕하세요, below you can find C# 2.0 Generic Free Pattern example that I just invented ;). Only generic code is invoked, but it is called without generic type. I have a better idea of implementing this pattern, but it needs the introduction of 3rd usage of our keyword in C#, and I cannot make it. 하지만, I could make this pattern, and I hope you like it. Now you can write generic code that is used like no generic needed, so it is like JavaScript in C# when you use it and strong typed generics when you write it ;).

namespace GenericFreePattern
{
    using System;
    // Framework Code
    internal class Comparer<T> : Comparer where T : IComparable, IComparable<T>
    {
        public Comparer(T x1, T x2)
        {
            this.x1 = x1;
            this.x2 = x2;
        }
        private readonly T x1;
        private readonly T x2;
        public override int Compare()
        {
            return x1.CompareTo(x2);
        }
    }
    public class Comparer
    {
        internal Comparer() {}
        private readonly Comparer instance;
        public Comparer(IComparable x1, IComparable x2) {
            if (x1.GetType() != x2.GetType())
                throw new InvalidOperationException(
                    "Arguments have different types!");
            instance = (Comparer)Activator.CreateInstance(
                typeof(Comparer<>)
                .MakeGenericType(x1.GetType()),
                new object[]{x1, x2});
        }
        public virtual int Compare()
        {
            return instance.Compare();
        }
    }
    // Client Code
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(
                "new Comparer(3,5).Compare() = {0}",
                new Comparer(3,5).Compare());
            Console.Write("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
}

피 ;).

“에 대한 답글 1개일반 자유 패턴”

  1. 핑백: Third usage of C# out keyword with Roslyn Intro @ coding by to design

답장을 남겨주세요

귀하의 이메일 주소는 공개되지 않습니다. 필요 입력 사항은 표시되어 있습니다 *

*

이 사이트는 스팸을 줄이기 위해 Akismet을 사용합니다.. 댓글 데이터가 처리되는 방법 알아보기.