gpt4 book ai didi

c# - 属性和方法之间的歧义

转载 作者:太空狗 更新时间:2023-10-30 00:30:22 25 4
gpt4 key购买 nike

来自here我的代码中有一些相同的东西。假设我有以下类(class):

public class EList<T> : List<T>
{
public string Add { get; set; }
}

现在我期待错误

Ambiguity between 'EList.Add' and 'EList.Add(int)'

但是下面的代码没有任何错误:

EList<int> il = new EList<int>();
il.Add(1);
il.Add = "test";

问题:继承是否错误地抑制了这个错误?

最佳答案

它在 C# 的成员查找规则中明确满足(C# Specification 7.4 节)。具体来说,这里重要的是可调用性

skipping earlier rules

  • Next, if the member is invoked, all non-invocable members are removed from the set. (The call to Add() is invoked. Therefore the Add property is removed from the set)

  • Next, members that are hidden by other members are removed from the set. For every member S.M in the set, where S is the type in which the member M is declared, the following rules are applied:

    • If M is a constant, field, property, event, or enumeration member, then all members declared in a base type of S are removed from the set. (The Add method in the base type is removed)

more rules

所以在这一点上,没有歧义,因为上面的两条规则已经消除了一个或另一个可能存在冲突的成员。

另见第 10.3 节,类(class)成员:

The name of a constant, field, property, event, or type must differ from the names of all other members declared in the same class.

The name of a method must differ from the names of all other non-methods declared in the same class. In addition ...

(我的重点)

还有,

The inherited members of a class type (§10.3.3) are not part of the declaration space of a class. Thus, a derived class is allowed to declare a member with the same name or signature as an inherited member

关于c# - 属性和方法之间的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37805317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com