侧边栏壁纸
博主头像
komi

Bona Fides

  • 累计撰写 9 篇文章
  • 累计创建 17 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

Ternary-operator in Interpolated Strings 三元表达式与插值字符串的坑

komi
2024-09-25 / 0 评论 / 0 点赞 / 22 阅读 / 217 字

起因

var baseList = await _repShareProfitBill.AsQueryable()
            .Where(profit => SqlFunc.ContainsArray(idList, profit.Id))
            .Select(profit => new
            {
                DateStr = $"{profit.Year}-{profit.Month}",
                DateSort = DateTime.Parse(
                    $"{profit.Year}-{profit.Month < 10 ? $"0{profit.Month}" : $"{profit.Month}"}-01"),
                profit.TargetId,
                profit.AmountMoney,
                profit.IsAccountingApproved,
                profit.IsOrgIssueInvoice,
                profit.IsAccountingPay
            })
            .ToListAsync();

自己在写业务逻辑的时候发现DateSort字段如果用普通的字符串插值写法貌似编译不通过

不明白为什么常用的三元表达式在字符串插值这个地方突然翻车了

解决方案

后来通过查阅资料发现这个问题在18年的时候就已经被提了Issue 貌似和字符串格式化相关

解决倒是也方便 直接在使用三元表达式的地方加上括号就可以正常使用了

DateTime.Parse($"{profit.Year}-{(profit.Month < 10 ? $"0{profit.Month}" : $"{profit.Month}")}-01")
0

评论区