有時候我想要在兩個字符串之間加入一個空格。但如果第二個字符串爲空,我不想要空間。如果字符串非空,則添加到字符串
請考慮下面的代碼:
void AssertFoo(bool cond, string message = null) {
...
Assert.Fail("Something is foo.{0}", message != null ? " " + message : "");
...
}
有沒有更優雅的方式來做到這一點?
有時候我想要在兩個字符串之間加入一個空格。但如果第二個字符串爲空,我不想要空間。如果字符串非空,則添加到字符串
請考慮下面的代碼:
void AssertFoo(bool cond, string message = null) {
...
Assert.Fail("Something is foo.{0}", message != null ? " " + message : "");
...
}
有沒有更優雅的方式來做到這一點?
這是我喜歡的一個選項。如果您的數據已經有IEnumerable<string>
,那麼更好,但即使您沒有,也很容易。它也清晰地擴展到正在連接的n個字符串,而不僅僅是1或2個。
string[] myStrings = new string[]{"Hello", "World", null};
string result = string.Join(" ", myStrings.Where(str => !string.IsNullOrEmpty(str)));
這是另一種選擇。它是這一個情況更短了一點,但它的醜陋,難讀,而不是作爲可擴展的,所以我可能會避免個人:
//note space added before {0}
Assert.Fail("Something is foo. {0}", message ?? "\b");
在這種情況下,我們的空間添加到格式字符串本身,但是如果message
爲空,我們應該使用退格字符來刪除我們知道的消息之前的空格。
試試這個:
string joinedString = string.IsNullOrEmpty(message2) ? message1 : message1 + " " + message2;
Assert.Fail("Something is foo.{0}", (" " + message).TrimEnd());
當然,這會導致一些字符串對象的創建,但是在絕大多數程序中這種微觀優化問題不太可能發生。這種方法可能被認爲是一個優點,它不僅處理空消息,而且處理所有空白消息。
對於您可以使用下面的擴展方法C#新版本:
public static string Prepend(this string value, string prepend) => prepend + value;
它可以像這樣使用:
Assert.Fail("Something is foo.{0}", message?.Prepend(" "));
我認爲。如果需要,我希望可以選擇使用{0},{1},{2}。它的可讀性也不如我已有的。 –