如何优雅地类型转换和非空判断

提问

如何优雅地类型转换和非空判断

回答

使用模式匹配

😥 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;
posted @ 2023-09-28 09:28  东百牧码人  阅读(17)  评论(0)    收藏  举报