簡體   English   中英

C#傳遞類型為object的可選參數

[英]C# passing an optional parameter of type object

我在這里獲得了帶有字符串參數的代碼:

public static void DisplayText(string Default)
{
    foreach (char c in Default)
    {
        Console.Write(c);
        Thread.Sleep(25);
    }
}

現在,我需要的是能夠使此代碼起作用,以便它也可以采用多個參數:

DisplayText("Welcome to you, {0} the {1}.", player.Name, player.Class);

但是我還需要僅能將字符串參數與可為空的對象參數放在一起。 我在這里嘗試了這段代碼:

我嘗試使用nullable <>,但是卻無濟於事。

現在,有指針嗎?

為什么不將String.Format()與您的輸入一起使用。

因此致電:

DisplayText(String.Format("Welcome to you, {0} the {1}.", player.Name, player.Class));

String.Format()接受一個字符串以及分配給{0}和{1}位置的其他字符串組成的數組( params )。

IE

string str = String.Format("Welcome to you, {0} the {1}.", player.Name, player.Class);
DisplayText(str);
//str = "Welcome to you, bob the greatest"

否則,您將需要根據需要創建一個重載的DisplayText()方法。

就像是:

 private static void DisplayText(string message, params string[] otherStrings)
 {       
   // otherStrings will be null or contain an array of passed-in-strings 
        string str = string.Format(message, otherString);
        foreach (char c in str)
        {
            Console.Write(c);
            Thread.Sleep(25);
        }       
 }

當您鍵入DisplayText();時,執行重載方法將為您提供2種選擇DisplayText(); 每個簽名一個。

在尋找我的答案之一時,我在這里提出了自己的評論。 我知道已經解決了這個問題,但是您也可以使用String Interpolation (C#6.0)並保持您的方法不變。

public static void DisplayText(string Default)
{
    //I have simplified the method but you get the point
    Console.WriteLine(Default);
}

class Player
{
    public string Name { get; set; }
    public string Class { get; set; }
}

public static void Main()
{
    Player player = new Player();
    player.Name = "uTeisT";
    player.Class = "Novice";

    //Passing the parameter with new feature
    //Results in more readable code and ofc no change in current method
    DisplayText($"Welcome to you, {player.Name} the {player.Class}.");
}

輸出將是:

歡迎您,初學者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM