[英]Deconstruct tuple for pattern matching
Given a function async Task<(Boolean result, MyObject value)> TryGetAsync()
, I can do给定一个函数
async Task<(Boolean result, MyObject value)> TryGetAsync()
,我可以做到
if((await TryGetAsync()) is var ret && ret.result)
{
//use ret.value
}
But if I try to use declare the types or use deconstruction get an error "a declaration is not allowed in this context":但是,如果我尝试使用声明类型或使用解构得到错误“在此上下文中不允许声明”:
//declaration. error
if((await TryGetAsync()) is (Boolean result, MyObject value) ret && ret.result)
{
//use ret.value
}
//deconstruction, also error.
if((await TryGetAsync()) is (Boolean result, MyObject value) && result)
{
//use value
}
How can I avoid using the first option var ret
in this scenario?在这种情况下如何避免使用第一个选项
var ret
? My issue with this is that the types are not evident (which is a separate discussion).我的问题是类型不明显(这是一个单独的讨论)。
The pattern matching specification doesn't allow the value tuple notation as a valid type_pattern
in the pattern matching grammar. 模式匹配规范不允许将值元组表示法作为模式匹配语法中的有效
type_pattern
。
The tuple notation is rewritten in the compiler to use ValueTuple
.元组符号在编译器中被重写以使用
ValueTuple
。 So there is an option: it does work with the underlying type, ValueTuple<bool, MyObject>
:所以有一个选项:它确实适用于基础类型
ValueTuple<bool, MyObject>
:
if ((await TryGetAsync()) is ValueTuple<bool, MyObject> ret && ret.Item1)
While not ideal, it could provide you with a workaround.虽然不理想,但它可以为您提供解决方法。
In C# 8.0 you can use your last option and get no error:在 C# 8.0 中,您可以使用最后一个选项并且不会出错:
if((await TryGetAsync()) is (Boolean result, MyObject value) && result)
{
//use value
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.