51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

使用C# 7元组进行模式匹配。

英文:

Use pattern matching with a C# 7 tuple

问题 {#heading}

以下是已翻译的代码部分:

object foo = ("hello", "world");
if (foo is (string, string) bar) { Console.WriteLine(bar.Item1); }

请注意,我只翻译了代码部分,没有包含问题或其他内容。如果您需要进一步的帮助,请随时提出。 英文:

I have the following code:

object foo = ("hello", "world");
var bar = foo as (string, string)?;
if (bar != null) { Console.WriteLine(bar.Value.Item1); }

Edit: I should say that foo is just an example of a variable I might receive in object form but should be able to convert.

Resharper highlights the 'as (string, string)' and suggests I Use Pattern Matching and when I accept, this is the result:

object foo = ("hello", "world");
if (foo is (string, string) bar) { Console.WriteLine(bar.Item1); }

This looks like it should be ok but it does not compile as (string, string) is highlighted with the error No 'Deconstruct' method with 2 out parameters found for type 'object'

While this code transformation seems like a resharper bug, this is not strictly a resharper-specific question as I'd like to know how should I write this? My original code worked fine but is there a way I can do what my original code is doing with pattern matching?

答案1 {#1}

得分: 2

抱歉,Resharper使您的代码出现错误。

var bar = foo as (string, string)?; // foo 被强制转换为元组
...
if (foo is (string, string) bar) // 这里没有强制转换,foo 仍然是对象

var foo = ("hello", "world"); // 这里可能是解决方案,重构后的对象会引发错误

英文:

Unfortunately resharper made your code erroneous.

var bar = foo as (string, string)?; // foo casts to tuple
...
if (foo is (string, string) bar) // there is no cast, foo is still object

var foo = ("hello", "world"); // can be a solution here, object causes the error after refactoring

赞(0)
未经允许不得转载:工具盒子 » 使用C# 7元组进行模式匹配。