c# – 捕获null-coalescing运算符中左手项成功分配的变量

前端之家收集整理的这篇文章主要介绍了c# – 捕获null-coalescing运算符中左手项成功分配的变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用??运算符尝试根据列表中找到的最佳匹配来分配对象.

我有各种匹配规则,但为此示例简化了这一点:

objectImTryingToSet =
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking numerous things*/) ??                  //rule1
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking different numerous things*/) ??        //rule2
MyListOfPotentialMatches.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" }                 //rule1
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking different numerous things*/) ??  if (objectImTryingToSet != null) { ruleThatMatched = "rule2" }       //rule2
MyListOfPotentialMatches.FirstOrDefault(*/lamda checking again different numerous things*/); if (objectImTryingToSet != null) { ruleThatMatched = "rule3"}     //rule3

//tried all the rules and still no match
if (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;
}
原文链接:https://www.f2er.com/csharp/244854.html

猜你在找的C#相关文章