如何优雅地类型转换和非空判断
提问
如何优雅地类型转换和非空判断
回答
使用模式匹配
😥 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;

浙公网安备 33010602011771号