提問
如何優雅地類型轉換和非空判斷
回答
使用模式匹配
😥 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;