緣起
在撰寫 Console 程式時, 常常會需要重複一些字元, 作為區隔符號, 通常以下即可;
但受限於傳入的參數僅能為 Char, 所以如果需要 2 個以上的字元 (即一個字串), 就無法作到. 因此, 上網查了一下, 有一篇文章 (Best way to repeat a character in C#) 有提到可以撰寫擴充方法 ...
Console.WriteLine(new string('=', 40));
但受限於傳入的參數僅能為 Char, 所以如果需要 2 個以上的字元 (即一個字串), 就無法作到. 因此, 上網查了一下, 有一篇文章 (Best way to repeat a character in C#) 有提到可以撰寫擴充方法 ...
程式範例
以下範例來自 Best way to repeat a character in C#
(1) 建立一個擴充方法的類別
(2) 呼叫範例
(1) 建立一個擴充方法的類別
public static class StringExtensions
{
//回傳重複的 "字元" 所組成的字串
public static string Repeat(this char chatToRepeat, int repeat)
{
return new string(chatToRepeat, repeat);
}
//回傳重複的 "字串" 所組成的字串
public static string Repeat(this string stringToRepeat, int repeat)
{
var builder = new StringBuilder(repeat * stringToRepeat.Length);
for (int i = 0; i < repeat; i++)
{
builder.Append(stringToRepeat);
}
return builder.ToString();
}
}
(2) 呼叫範例
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("以下採用擴充方法 Repeat with char --> '-'.Repeat(40)");
Console.WriteLine('-'.Repeat(40));
Console.WriteLine("");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("以下採用擴充方法 Repeat with String --> \"#$\".Repeat(20)");
Console.WriteLine("#$".Repeat(20));
Console.WriteLine("");

沒有留言:
張貼留言