C# 7元组模式匹配写法咨询:Resharper转译代码编译失败
如何用模式匹配实现值元组从object的安全转换?
问题背景
原代码通过as操作符将object类型变量安全转换为可空值元组,逻辑可以正常运行:
object foo = ("hello", "world"); var bar = foo as (string, string)?; if (bar != null) { Console.WriteLine(bar.Value.Item1); }
但Resharper建议使用模式匹配后生成的代码无法编译,报错信息为:No 'Deconstruct' method with 2 out parameters found for type 'object':
object foo = ("hello", "world"); if (foo is (string, string) bar) { Console.WriteLine(bar.Item1); }
正确的模式匹配写法
写法1:明确指定值元组类型做匹配
直接使用值元组的正式类型ValueTuple<string, string>进行类型模式匹配,编译器会正确识别为类型检查而非解构操作:
object foo = ("hello", "world"); if (foo is ValueTuple<string, string> bar) { Console.WriteLine(bar.Item1); }
写法2:匹配可空值元组并校验有效性
和原代码逻辑完全一致,通过模式匹配绑定可空值元组变量,再判断是否包含有效值:
object foo = ("hello", "world"); if (foo is (string, string)? bar && bar.HasValue) { Console.WriteLine(bar.Value.Item1); }
写法3:类型匹配+解构一步完成
如果想同时完成类型验证和元组元素提取,可以结合类型模式与解构语法,直接绑定元组的元素变量:
object foo = ("hello", "world"); if (foo is ValueTuple<string, string> (item1, item2)) { Console.WriteLine(item1); }
报错原因解析
Resharper生成的foo is (string, string) bar会被编译器解析为解构模式,而非类型匹配模式。该模式会尝试调用object类型的Deconstruct方法来提取两个参数,但object并没有定义这个方法,因此触发编译错误。正确的类型匹配需要明确指定元组的具体类型,或者使用可空元组的写法来触发正确的类型检查逻辑。
内容的提问来源于stack exchange,提问作者randonoob
相关产品推荐
相关产品推荐

