C# 6.0:String Interpolation

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   使用   sp   

在開發中經常需要對字串進行格式化處理。我們一般使用String.Format()方法,它會將指定字串中的每個格式項替換為相應對象的值的文本等效項。雖然這很普通,但有時會容易使人迷惑並造成錯誤。因為,我們需要為每一個格式化項指定預留位置並將他們和實際的對象值對應起來。我們還要保證我們給每一個預留位置都賦了對應的值。C#6.0中的String Interpolation使這字串格式化變的大為簡潔。使用String Interpolation,我們不再需要使用預留位置,可以直接引用我們的值。

這裡是一個使用String interpolation的簡單例子。

string Value1 = "Value 1";string Value2 = "Value 2";// With String.Formatvar stringValue1 = string.Format("{0}- {1}", Value1, Value2);// With String Interpolationvar stringValue2 = "\{Value1}-\{Value2}";
View Code

在上面的代碼塊中stringValue1和stringValue2返回同樣的值,但String Interpolation使代碼看起來更簡單,也更不容易出錯。當要格式化一個有大量屬性值的字串用來顯示時,你可以簡單的在對應的地方放對應的值,而不需要使用預留位置。

C# 6.0:String Interpolation

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.