简体   繁体   中英

C# passing an optional parameter of type object

I got this code here that takes a string parameter:

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

Now, what I need is to be able to make this code works so it can also take multiple parameters:

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

But I also need to be able to only put a string parameter with nullable object parameters. I tried this code here:

I tried using the nullable<> but It got me nowhere.

Now, any pointers?

Why not use String.Format() with your input.

So call:

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

String.Format() takes a string plus an array ( params ) of other strings, that are assigned to the {0} and {1} locations.

IE

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

Failing that, you will need to create an overloaded DisplayText() method with your requirements.

Something like:

 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);
        }       
 }

Doing the overload method will give you 2 options in your intellisense when you type DisplayText(); one for each of the signatures.

While looking for one of my answers, I came up with my comment here. I know this has already been answered but, you can also use String Interpolation (C# 6.0) and keep your method as it is.

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}.");
}

And the output will be:

Welcome to you, uTeisT the Novice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM