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

huangapple go评论100阅读模式
英文:

Use pattern matching with a C# 7 tuple

问题

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

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

得分: 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

huangapple
  • 本文由 发表于 2023年8月11日 01:33:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76878084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定