Generic Free Pattern

Merhaba, 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. Fakat, 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);
        }
    }
}

P ;).

Generic Free Pattern&rdquo İçin bir yorum;

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

Cevap bırakın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar işaretlendi *

*

Bu site spam'ı azaltmak için Akismet'i kullanıyor. Yorum verilerinizin nasıl işlendiğini öğrenin.