Microsoft的F#指南为什么不建议从将被C#使用的代码中返回元组?

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

Why do the Microsoft guidelines for F# not recommend returning a tuple from code that will be used by C#?

问题

根据F#指南,不建议将元组作为从C#消耗的代码的返回类型。

避免使用元组作为返回值

两种语言之间似乎对元组有很好的兼容性,尤其是在较新的版本中。所以,我不太明白这个建议的意义。我计划返回一个结构体,以避免这些指南可能考虑到的任何问题。

他们提供的解释很模糊。

通常不会为.NET开发人员提供理想和预期的API。

这究竟是什么意思?如果我不理会这个建议,继续返回元组,会遇到什么问题?

英文:

According to the F# guidelines, tuples as a return type from F# are not recommended for code that will be consumed from C#.

Avoid using tuples as return values.

There seems to be good compatibility for tuples between the two languages. Especially in the newer versions. So, I don't quite understand this recommendation. I'm planning to return a struct instead to avoid whatever the harm is that these guidelines must have in mind.

The explanation they give is vague.
>they will most often not provide the ideal and expected API for .NET developers.

What does this mean exactly? What pitfalls can I expect to run into if I ignore this and return tuples anyway?

答案1

得分: 4

我认为对你的问题的直接答案是,大多数C#和.NET API不返回元组。最初是因为旧版本的C#不支持元组,但现在它已经成为一种已经建立的模式,不管好坏。F#的指导原则只是遵循最小惊讶原则

例如,考虑Dictionary.TryGetValue

public bool TryGetValue (TKey key, out TValue value);

F#会自动将其转换为TKey -> (bool * TValue),但事实仍然是在C#中不期望元组返回类型。

因此,如果你是API的使用者,当然可以按照你现在想要的方式来定义它。但如果这是一个将由典型的C#开发人员使用的公共API,我强烈建议遵循已建立的模式,即使它可能更难看。

话虽如此,元组返回类型可能(而且可能应该)在C#和.NET中变得更加常见。如果是这样,我预计F#的设计指南最终也会进行更新。

英文:

I think the direct answer to your question is that most C# and .NET API's don't return tuples. Originally, this was because older versions of C# didn't support tuples, but now it is an established pattern, for better or worse. The F# guideline simply follows the principle of least surprise.

For example, consider Dictionary.TryGetValue:

public bool TryGetValue (TKey key, out TValue value);

F# automatically converts this to TKey -> (bool * TValue), but the fact remains that the tuple return type is not expected in C#.

So, if you're the consumer of the API, then of course you should define it the way you want now. But if this is a public API that will be consumed by typical C# developers, I would strongly consider following the established pattern, even if it is uglier.

That said, tuple return types might (and probably should) become more common in C# and .NET over time. If so, I expect the F# design guideline will eventually be updated as well.

huangapple
  • 本文由 发表于 2023年6月22日 05:34:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527298.html
匿名

发表评论

匿名网友

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

确定