我有各种匹配规则,但为此示例简化了这一点:
objectImTryingToSet =MylistofPotentialMatches.FirstOrDefault(*/lamda checking numerous things*/) ?? //rule1MylistofPotentialMatches.FirstOrDefault(*/lamda checking different numerous things*/) ?? //rule2MylistofPotentialMatches.FirstOrDefault(*/lamda checking again different numerous things*/); //rule3
出于调试的目的,我想存储一个字符串日志记录,哪个规则是成功分配了objectImTryingToSet的规则,因为我在一个场景中有一个BUG wherby,当它不应该被分配时,它是一个真正令人头疼的手动尝试筛选通过所有这些规则来找出错误分配的位置.
所以我基本上想要,伪:
string ruleThatMatched = null;objectImTryingToSet =MylistofPotentialMatches.FirstOrDefault(*/lamda checking numerous things*/) ?? if (objectImTryingToSet != null) { ruleThatMatched = "rule1" } //rule1MylistofPotentialMatches.FirstOrDefault(*/lamda checking different numerous things*/) ?? if (objectImTryingToSet != null) { ruleThatMatched = "rule2" } //rule2MylistofPotentialMatches.FirstOrDefault(*/lamda checking again different numerous things*/); if (objectImTryingToSet != null) { ruleThatMatched = "rule3"} //rule3//trIEd all the rules and still no matchif (objectImTryingToSet == null){ ruleThatMatched = "no rule managed to find a match";}
这甚至可以用?? *** 作符?
解决方法 你可以这样做:var res = MylistofPotentialMatches.Select(v => new {r=1,v}).FirstOrDefault(/*lamda checking numerous things*/) ?? MylistofPotentialMatches.Select(v => new {r=2,v}).FirstOrDefault(/*lamda checking different numerous things*/) ?? MylistofPotentialMatches.Select(v => new {r=3,v}).FirstOrDefault(/*lamda checking again different numerous things*/);if (res != null) { var ruleNumber = res.r; objectImTryingToSet = res.v;}
关键是Select,它将结果与硬编码规则编号配对.
请注意,你可以不用?? *** 作符:
var firstChoice = MylistofPotentialMatches.Select(v => new {r=1,v}).Where(/*lamda checking numerous things*/);var secondChoice = MylistofPotentialMatches.Select(v => new {r=2,v}).Where(/*lamda checking different numerous things*/);var thirdChoice = MylistofPotentialMatches.Select(v => new {r=3,v}).Where(/*lamda checking again different numerous things*/);var res = firstChoice.Concat(secondChoice).Concat(thirdChoice).FirstOrDefault();if (res != null) { var ruleNumber = res.r; objectImTryingToSet = res.v;}总结
以上是内存溢出为你收集整理的c# – 捕获null-coalescing运算符中左手项成功分配的变量全部内容,希望文章能够帮你解决c# – 捕获null-coalescing运算符中左手项成功分配的变量所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)