寧波seo排名費(fèi)用安卓優(yōu)化大師2021
- 點(diǎn)擊跳轉(zhuǎn)=>Unity3D特效百例
- 點(diǎn)擊跳轉(zhuǎn)=>案例項(xiàng)目實(shí)戰(zhàn)源碼
- 點(diǎn)擊跳轉(zhuǎn)=>游戲腳本-輔助自動(dòng)化
- 點(diǎn)擊跳轉(zhuǎn)=>Android控件全解手冊(cè)
- 點(diǎn)擊跳轉(zhuǎn)=>Scratch編程案例
- 點(diǎn)擊跳轉(zhuǎn)=>軟考全系列
👉關(guān)于作者
專注于Android/Unity和各種游戲開發(fā)技巧,以及各種資源分享(網(wǎng)站、工具、素材、源碼、游戲等)
有什么需要?dú)g迎底部卡片私我,交流讓學(xué)習(xí)不再孤單。
👉實(shí)踐過程
😜問題
這兩天,我想封裝一個(gè)方法:
private fun strFormatTwo(format: String, vararg args: Any): String {return String.format(format, args)
}
傳遞兩個(gè)參數(shù),一個(gè)是轉(zhuǎn)換格式,一個(gè)是可變參數(shù)。
調(diào)用:strFormatTwo(“%04x”,20,30)
一運(yùn)行就會(huì)報(bào)錯(cuò)。
java.util.IllegalFormatConversionException: x != [Ljava.lang.Object;
這就很莫名其妙,但是為什么系統(tǒng)的 String.format 就可以這樣操作呢?
我點(diǎn)擊去看源碼:
發(fā)現(xiàn)它有個(gè)星號(hào)(*),開始查閱資料。
😜解決
查了一下。星號(hào)的作用是,在數(shù)組對(duì)象前加*號(hào)可以將數(shù)組展開,以方便傳值。
展開?這有什么可展開的?難道傳遞的少了?
咱們寫個(gè)方法測(cè)試一些:
private fun strFormat(format: String, vararg args: Any): String {Log.e("TAG", "strFormat: "+args.size)return String.format(format, args)
}private fun strFormatTwo(format: String, vararg args: Any): String {Log.e("TAG", "strFormatTwo: "+args.size)return strFormat(format, args)
// return String.format(format, args)
}//調(diào)用
strFormatTwo("%04x",20,30)
上面方法因?yàn)橄到y(tǒng)的 String.format 里面沒法打日志,我們只好再寫一個(gè)方法,這樣調(diào)用一下。
strFormatTwo 調(diào)用系統(tǒng) String.format 和 strFormatTwo 調(diào)用咱們寫的 strFormat 方法形式是一樣。
我們先調(diào)用 strFormatTwo 看到日志輸出的是 2 個(gè)長度單位,在 strFormat 中輸出卻成為了一個(gè)長度。
private fun strFormat(format: String, vararg args: Any): String {return String.format(format, *args) //帶星號(hào)正確寫法
}
這是因?yàn)?Java 中的 vararg 參數(shù)在被傳遞給 String.format() 方法時(shí),會(huì)自動(dòng)被轉(zhuǎn)換為一個(gè)數(shù)組。這表示我們將 args 數(shù)組作為參數(shù)傳遞給 String.format() 方法。這樣做是為了確保 args 數(shù)組能夠以參數(shù)的形式傳遞給 String.format() 方法,以便正確地進(jìn)行格式化字符串。 而在出現(xiàn)問題的函數(shù)中,我們使用了 “String.format(format, args)” 的寫法,這表示我們將 args 作為一個(gè)單個(gè)的參數(shù)傳遞給 String.format() 方法。這樣做會(huì)導(dǎo)致 args 數(shù)組無法正確傳遞給 String.format() 方法,從而導(dǎo)致錯(cuò)誤。 因此,為了確保 args 數(shù)組能夠以參數(shù)的形式傳遞給 String.format() 方法,我們應(yīng)該使用第一個(gè)函數(shù)的實(shí)現(xiàn)方式,即使用 “String.format(format, *args)” 的寫法。
同理,如果你自己的其他函數(shù)參數(shù)也是可變數(shù)組的,而傳遞的也是數(shù)組,使用的時(shí)候就需要添加*
👉其他
📢作者:小空和小芝中的小空
📢轉(zhuǎn)載說明-務(wù)必注明來源:https://zhima.blog.csdn.net/
📢這位道友請(qǐng)留步??,我觀你氣度不凡,談吐間隱隱有王者霸氣💚,日后定有一番大作為📝!!!旁邊有點(diǎn)贊👍收藏🌟今日傳你,點(diǎn)了吧,未來你成功??,我分文不取,若不成功??,也好回來找我。
溫馨提示:點(diǎn)擊下方卡片獲取更多意想不到的資源。