AidaHagh / C-Sharp

Learn C#
1 stars 0 forks source link

Delegates #30

Open AidaHagh opened 3 months ago

AidaHagh commented 3 months ago

دلیگیت‌ها (Delegates) نوعی متغیر هستند که می‌توانند به یک متد اشاره کنند. یک مثال ساده از دلیگیت:

class Program {

public delegate void MyDelegate(string message);
public static void ShowMessage(string message)
{
    Console.WriteLine(message);
}

static void Main(string[] args)
{
    MyDelegate del = new MyDelegate(ShowMessage);
    del("Hello, World!");
}

}

AidaHagh commented 3 months ago

مثال 2: استفاده از دلیگیت برای مرتب‌سازی اگر comparison(array[i], array[j]) > 0 باشد، به این معنی است که array[i] (بزرگتر) باید بعد از array[j] (کوچکتر) قرار گیرد (در مرتب‌سازی صعودی) یا بالعکس (در مرتب‌سازی نزولی). اگر شرط comparison(array[i], array[j]) > 0 برقرار باشد، دو عنصر array[i] و array[j] با یکدیگر جابجا می‌شوند.روند کار حلقه ها بصورت عکس زیر است(عکس برای مرتب سازی صعودی).


public class Program {

public delegate int Comparison(int x, int y);// تعریف دلیگیت برای مقایسه دو عدد

public static int CompareAscending(int x, int y)    // متدی که با امضای دلیگیت سازگار است
{
    return x.CompareTo(y);
}
public static int CompareDescending(int x, int y)
{
    return y.CompareTo(x);
}
public static void Sort(int[] array, Comparison comparison)
{
    for (int i = 0; i < array.Length - 1; i++)
    {
        for (int j = i + 1; j < array.Length; j++)
        {
            if (comparison(array[i], array[j]) > 0)
            {
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
}

public static void Main()
{
    int[] numbers = { 3, 1, 4, 1, 5, 9 };

    // مرتب‌سازی به ترتیب صعودی
    Sort(numbers, CompareAscending);
    Console.WriteLine("Sorted Ascending: " + string.Join(", ", numbers));

    // مرتب‌سازی به ترتیب نزولی
    Sort(numbers, CompareDescending);
    Console.WriteLine("Sorted Descending: " + string.Join(", ", numbers));
}

}


for-loop1

AidaHagh commented 3 months ago

مثال 3: دلیگیت‌های چندگانه استفاده از یک دلیگیت برای فراخوانی چندین متد .


class Program {

public delegate void ShowColor(string message);

public static void ChangeColor(string name)
{
    Console.WriteLine("Yellow " + name);
}

public static void ChangeColor2(string name)
{
    Console.WriteLine("Blue " + name);
}

public static void ChangeColor3(string name)
{
    Console.WriteLine("Red " + name);
}

public static void ChangeColor4(string name)
{
    Console.WriteLine("Green " + name);
}

static void Main(string[] args)
{
    ShowColor showColor = new ShowColor(ChangeColor);
    showColor += ChangeColor2;
    showColor += ChangeColor3;
    showColor += ChangeColor4;

    showColor -= ChangeColor3;

    showColor("Dress");     //نتیجه: Yellow Dress
                                 // Blue Dress
                                 // Green Dress

    Console.ReadLine();
}

}