如何優雅地類型轉換和非空判斷

提問

如何優雅地類型轉換和非空判斷

回答

使用模式匹配

😥 BAD

 Bytes2ValueAttribute attr = (Bytes2ValueAttribute) Attribute.GetCustomAttribute(p, typeof(Bytes2ValueAttribute));
 if (attr != null)
 {
     // TODO : something;

😜 GOOD

 if (Attribute.GetCustomAttribute(p, typeof(Bytes2ValueAttribute)) is Bytes2ValueAttribute attr)
 {
     // TODO : something;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章