Generic Method ve IComparable<T> arabirimi

Bazen bir methada farklı tiplerde parametre geçirmek veyadöndürmek isteyebilirsiniz. Bu metodu da bazı koşullu olarak bazı yerlerde kullanmak isteyebiliriz. Bu gibi durmlarda gereric methodlar kullanacağız. IComparable<> arabirimi Compare isminde int değer dondurren bir method içerir.  Bu değer Nesne parametredeki nesneden buyukse 1, eşitse 0, kucukse -1 değer dondurur. Array sınıfının Sort methodu dolaylı olarak bu arabirimi kullanır.

using System;

namespace GenericMethodlar
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 5, b = 26;
            Degistir<int>(ref a, ref b);
            Console.WriteLine("a={0},  b={1}",a,b);

            //a = 7;
            BuyukseDegistir(ref a, ref b);
            Console.WriteLine("a={0},  b={1}", a, b);
        }
        static void  Degistir<T> (ref T sag, ref T sol)
        {
            T gecici;
            gecici = sag;
            sag = sol;
            sol = gecici;
        }
        //şimdide ICompareble arabiriminden kalıtım almış iki nensneyi karşılaştıralım. Koşul her iki nesne karşılatıralaibilr olmalı.
        static void BuyukseDegistir<T>(ref T sag, ref T sol) where T : IComparable<T> 
        {
            T gecici;
            if (sag.CompareTo(sol) > 0)
            {
                gecici = sag;
                sag = sol;
                sol = gecici;
            }
        }
    }
}

 

Add comment

The file '/Custom/Widgets/Calendar/widget.cshtml' does not exist.The file '/Custom/Widgets/Category list/widget.cshtml' does not exist.The file '/Custom/Widgets/Tag cloud/widget.cshtml' does not exist.The file '/Custom/Widgets/Page List/widget.cshtml' does not exist.The file '/Custom/Widgets/Month List/widget.cshtml' does not exist.