C# 重載的幾種實現


算法重用是非常普遍的需求,在C#中可以使用如下手段實現,非常簡單,自己記錄一下,方便查詢。

以一個小功能為例來說明一下:打印1-5這5個數,和A-E這5個字符。

 

重載方式

static void Main(string[] args)
{
    PrintValues(1, 5);
    PrintValues('A', 'E');
    Console.ReadLine();
}


private static void PrintValues(int startIndex, int endIndex)
{
    if (startIndex > endIndex)
    {
        int temp = endIndex;
        endIndex = startIndex;
        startIndex = temp;
    }

    for (int i = startIndex; i <= endIndex; i++)
    {
        Console.WriteLine(i.ToString());
    }
}

private static void PrintValues(char startIndex, char endIndex)
{
    if (startIndex > endIndex)
    {
        char temp = endIndex;
        endIndex = startIndex;
        startIndex = temp;
    }

    for (char i = startIndex; i <= endIndex; i++)
    {
        Console.WriteLine(i.ToString());
    }
}

 

默認值方式

static void Main(string[] args)
{
    PrintValues(1);
    PrintValues('A');
    Console.ReadLine();
}


private static void PrintValues(int startIndex, int endIndex = 5)
{
    if (startIndex > endIndex)
    {
        int temp = endIndex;
        endIndex = startIndex;
        startIndex = temp;
    }

    for (int i = startIndex; i <= endIndex; i++)
    {
        Console.WriteLine(i.ToString());
    }
}

private static void PrintValues(char startIndex, char endIndex = 'E')
{
    if (startIndex > endIndex)
    {
        char temp = endIndex;
        endIndex = startIndex;
        startIndex = temp;
    }

    for (char i = startIndex; i <= endIndex; i++)
    {
        Console.WriteLine(i.ToString());
    }
}

好吧,對於很多含有默認值的函數來說,這個是有效減少重載的方式。

 

泛型方式
  這個例子我簡單試了一下,沒找到使用泛型合適的方式,壯士,教我!好在我直接使用dynamic實現了,也不怎么糾結。看其中的交換的那個可能實現:

static void Main(string[] args)
{
    int startIndex = 1;
    int endIndex = 5;
    Swap<int>(ref startIndex, ref endIndex);

    char startCharIndex = 'A';
    char endCharIndex = 'E';
    Swap<char>(ref startCharIndex, ref endCharIndex);

    Console.ReadLine();
}

private static void Swap<T>(ref T startIndex, ref T endIndex)
{
    T temp = endIndex;
    endIndex = startIndex;
    startIndex = temp;
}

  當然了,強大的泛型可不是這么簡單貨,感興趣自己搜索。

 

dynamic方式

static void Main(string[] args)
{
    PrintValues(1, 5);
    PrintValues('A', 'E');
    Console.ReadLine();
}

private static void PrintValues(dynamic startIndex, dynamic endIndex)
{
    if (startIndex > endIndex)
    {
        dynamic temp = endIndex;
        endIndex = startIndex;
        startIndex = temp;
    }

    for (dynamic i = startIndex; i <= endIndex; i++)
    {
        Console.WriteLine(i.ToString());
    }
}

 

  簡單,當只需要運行時行為的時候,或者是不希望編輯器檢查的時候,dynamic真是方便。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM