我有一部分我真的不喜欢的代码,如果有可能以某种方式简化它 – 会非常好.
A a; // I want to get rid of this variable if((a = collection.FirstOrDefault(x => x.Field == null)) != null) { throw new ScriptException("{0}",a.y); //I need to access other field of the object here,that's why I had to declare a variable outside of the expression }
解决方法
如果要组合变量赋值和定义,则可以使代码更具可读性:
A a = collection.FirstOrDefault(x => x.Field == null); if(a != null) throw new ScriptException("{0}",a.y);