在 C# 7.0 中使用元组和字段名称规则覆盖方法

Overriding Methods with Tuples and Field Name Rules in C# 7.0

我正在阅读 Visual Studio 17 RC 的这篇 page, which is officially referenced in the release notes,其中说明如下:

For the purpose of Overloading Overriding Hiding, tuples of the same types and lengths as well as their underlying ValueTuple types are considered equivalent. All other differences are immaterial.

When overriding a member it is permitted to use tuple types with same or different field names than in the base member.

A situation where same field names are used for non-matching fields between base and derived member signatures, a warning is reported by the compiler

试一试时:

public abstract class Foo
{
    public abstract void AbstractTuple((int a, string b) tuple);

    public virtual void OverrideTuple((int a, string b) tuple)
    {
        Console.WriteLine($"First= {tuple.a}  Second = {tuple.b}");
    }
}

public class Bar : Foo
{
    public override void AbstractTuple((int c, string d) tuple)
    {
        Console.WriteLine($"First= {tuple.c}  Second= {tuple.d}");
    }

    public override void OverrideTuple((int c, string d) tuple)
    {
        base.OverrideTuple(tuple);
    }
}

我收到以下错误:

Error CS8139 'Bar.AbstractTuple((int c, string d))': cannot change tuple element names when overriding inherited member 'Foo.AbstractTuple((int a, string b))'

Error CS8139 'Bar.OverrideTuple((int c, string d))': cannot change tuple element names when overriding inherited member 'Foo.OverrideTuple((int a, string b))'

问题是:

  1. 难道官方的设计注释有误?或者这是尚未在官方 C# 7.0 版本中实现的行为?

  2. 如果这是正确的行为,那么覆盖方法中的元组字段名称必须相同是否有意义?请记住,具有相同元组 (int a, int b)(int c, int d) 的两个方法不被视为过载候选者并会产生错误!

  3. 我们有官方的 C# 7.0 功能文档吗?

Is the official design Notes wrong? Or is this a behavior that is yet to be implemented in the official C# 7.0 Release?

据我所知,文档已过时。 That document hasn't significantly changed since April 2016, while the error that you got (ERR_CantChangeTupleNamesOnOverride in Roslyn source) was introduced in August 2016(不要被不同的错误代码搞糊涂了,那是后来改的)。

If this is the correct behavior, does it make sense that the tuple Field Names has to be the same in the overridden method? Keeping in might that two methods with same Tuples (int a, int b) and (int c, int d) are not considered overload candidates and generate an error!

是的,这似乎是新的预期行为。

Do we have official C# 7.0 Features documentation somewhere?

考虑到 C# 7.0 仍在开发中,文档是一个问题。 .Net 官方文档中有一篇关于元组的文章 is currently under review,尽管它根本没有提到这些问题。

因此,您找到的过时文档可能是目前最好的来源。 I have created an issue asking for the documentation to be updated.