為什么我不能使用以下代碼將變數值添加到字串中:
throw new ArgumentOutOfRangeException("Any Opening Type besides 'None', should have a minimum width value of 50. Your inputed value = {0}",value);
我得到的錯誤是:“CS1503:引數 2:無法從 'int' 轉換為 'System.Exception?'”
但是當我使用這段代碼時,它作業正常:
throw new ArgumentOutOfRangeException($"Any Opening Type besides 'None', should have a minimum width value of 50. Your inputed value = {value}");
有人可以幫我理解為什么嗎?據我所知,這兩種方式的結果應該是相同的。我不明白它為什么會轉換,如果我使用 console.WriteLine 方法,我不應該得到同樣的錯誤嗎?這有什么特別之處?
uj5u.com熱心網友回復:
第一種語法僅適用于使用格式字串的方法。一些方法,比如Console.WriteLine,有一個多載,它將格式字串作為第一個引數,將任意數量的物件作為后續引數陣列,因此您可能已經習慣了它的作業方式與使用字串插值語法 ( $"...") 時相同。
大多數例外建構式不遵循該模式,因此您必須構建自己的字串以作為它們的訊息引數傳入。正如您所發現的,字串插值語法會自動為您執行此操作。或者您可以string.Format顯式呼叫:
throw new ArgumentOutOfRangeException(
string.Format(
"Any Opening Type besides 'None', should have a minimum width value of 50. Your inputed value = {0}",
value));
uj5u.com熱心網友回復:
您應該查看ArgumentOutOfRangeException的建構式的檔案。您提供的引數與任何建構式引數型別都不匹配,因此會引發例外。
相反,您應該使用以下格式格式化字串String.Format():
throw new ArgumentOutOfRangeException(String.Format("Any Opening Type besides 'None', should have a minimum width value of 50. Your inputed value = {0}",value));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489158.html
