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

标签 c# overriding c#-7.0

我正在读这个page ,在 release notes 中正式引用Visual Studio 17 RC,它声明如下:

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 ,而您遇到的错误(Roslyn 源中的 ERR_CantChangeTupleNamesOnOverride)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.

关于c# - 在 C# 7.0 中使用元组和字段名称规则覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40831355/

相关文章:

c# - 将图表系列数据复制到另一个图表

c# - 继承 Exception 类以记录所有后续发生的异常

c# - DataContract 序列化 - 基类、继承和覆盖

c++ - 强制转换是可覆盖的操作吗?如果是这样,如何?

c# - 使用 discard 关键字丢弃任务会导致任何副作用吗?

c# - 模式匹配变量范围

c# - 如何包装一个很长的单词

C# 在继承链下覆盖多个派生类的基类方法

c# - 字符串上的模式匹配

c# - Visual C# 如何使使用我的程序的人不必安装 MySql 框架