C#如何在变量

时间:2017-05-10 16:25:30

标签: c#

我得到了这行代码(C#)

Console.WriteLine("This is you {0}.", someclass.name);

我想要使用的是这部分:

private void ConsoleWriteColor(ConsoleColor color, string text)
{
    Console.ForegroundColor = color;
    Console.WriteLine(text);
    Console.ResetColor();
}

问题是,我无法将带有{0}值的字符串传输到ConsoleWriteColor的参数文本中。

解决方案

string para = string.Format("Some text {0}",parameter);

3 个答案:

答案 0 :(得分:2)

您可以将params argument传递给您的ConsoleWriteCOlor

private void ConsoleWriteColor(ConsoleColor color, string text, params object[] prms)
{
    Console.ForegroundColor = color;
    Console.WriteLine(string.Format(text, prms));
    Console.ResetColor();
}

现在你可以这样称呼它

ConsoleWriteColor(ConsoleColor.DarkRed, "Hello {0} It is {1}", "Steve", DateTime.Today.DayOfWeek.ToString());

请注意,此方法没有检查传递给函数的正确参数数量。您可以传递少于格式字符串所期望的参数并获得异常(尽管同样的异常也会直接写入没有此函数的string.Format)

答案 1 :(得分:1)

使用string.Format("Some text {0}",parameter);这将插入您的参数并返回字符串。以下是如何做到这一点的示例:

public static void Main(string[] args)
{
    //Your code goes here
    Console.WriteLine("Hello, world!");
    ConsoleWriteColor(ConsoleColor.Red,"Hello {0} and {1}","Arthur","David")
}

private static void ConsoleWriteColor(ConsoleColor color, string text,params object[] a)
{
    Console.ForegroundColor = color;
    Console.WriteLine(string.Format(text,a));
    Console.ResetColor();
}

答案 2 :(得分:1)

您还应该检查C#6.0 Interpolated strings功能。我认为它更易读(你更喜欢,我希望)

您无需更改格式化方法或简单方法:

private void ConsoleWriteColor(ConsoleColor color, string text)
{
    Console.ForegroundColor = color;
    Console.WriteLine(text);
    Console.ResetColor();
}


string name1 = "Arthur";
string name2 = "David";

ConsoleWriteColor(ConsoleColor.Red, $"Hello {name1} and {name2}");  <-- notice the $