C# 7 Out 变量和模式变量声明不允许在查询子句中

标签 c# out c#-7.0

为什么查询子句中不允许使用 out 变量?

如果我在这里使用 out 变量,它会失败:

string json = "{'PayDays':['2017-07-07','2017-07-21','2017-08-04','2017-08-18']}";
var pd = JsonConvert.DeserializeObject<Accounting>(json);

var rm = from item in pd.PayDays
     where (DateTime.TryParse(item, out DateTime dateresult)) ?
    dateresult.Subtract(DateTime.Now).Days >= 0 ? true : false : false      
    select item;
rm.Dump();

但旧方法有效:

DateTime result;
var rm = from item in pd.PayDays
         where DateTime.TryParse(item, out result) ? (result.Subtract(DateTime.Now).Days >= 0 ? true : false) : false
         select item;
rm.Dump();

最佳答案

这是 relevant LDM notes .

结论:

We won't have time to do this feature in C# 7.0. If we want to leave ourselves room to do it in the future, we need to make sure that we don't allow expression variables in query clauses to mean something else today, that would contradict such a future.

The current semantics is that expression variables in query clauses are scoped to only the query clause. That means two subsequent query clauses can use the same name in expression variables, for instance. That is inconsistent with a future that allows those variables to share a scope across query clause boundaries.

Thus, if we want to allow this in the future we have to put in some restrictions in C# 7.0 to protect the design space. We have a couple of options:

  • Disallow expression variables altogether in query clauses
  • Require that all expression variables in a given query expression have different names

The former is a big hammer, but the latter requires a lot of work to get right - and seems at risk for not blocking off everything well enough.

We will neither do expression variables nor deconstruction in C# 7.0, but would like to do them in the future. In order to protect our ability to do this, we will completely disallow expression variables inside query clauses, even though this is quite a big hammer.

关于C# 7 Out 变量和模式变量声明不允许在查询子句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45065688/

相关文章:

c# - Selenium 测试在 IE11 中不起作用

vb.net - 目前在 ByRef 内部方法上指定 OutAttribute 有什么作用吗?

Html 渲染元素乱序

c# - .Net 4.5 和 4.0 中 Async 方法的 Out 关键字替换是什么?

c# - 将 C# 7 代码部署到 VSTS

linq-to-entities - 将匿名类型转换为新的C#7元组类型

c# - 如何修复这个特定的 "The call is ambiguous ..."

c# - Razor 输出@-webkit-keyframes

c# - 用于数字的正确数据类型是什么

C# 7 ValueTuple 编译错误