c# - 这是斯巴达,还是?

标签 c# inheritance types namespaces

下面是一道面试题。我想出了一个解决方案,但我不确定它为什么有效。


问题:

在不修改 Sparta 类的情况下,编写一些代码使 MakeItReturnFalse 返回 false

public class Sparta : Place
{
    public bool MakeItReturnFalse()
    {
        return this is Sparta;
    }
}

我的解决方案:(剧透)

公共(public)类地点
{
公共(public)接口(interface)斯巴达{}
}

但为什么 MakeItReturnFalse() 中的 Sparta 引用 {namespace}.Place.Sparta 而不是 {namespace}。斯巴达?

最佳答案

But why does Sparta in MakeItReturnFalse() refer to {namespace}.Place.Sparta instead of {namespace}.Sparta?

基本上,因为名称查找规则就是这么说的。在 C# 5 规范中,相关的命名规则在第 3.8 节(“命名空间和类型名称”)中。

第一对项目符号 - 截断和注释 - 阅读:

  • If the namespace-or-type-name is of the form I or of the form I<A1, ..., AK> [so K = 0 in our case]:
    • If K is zero and the namespace-or-type-name appears within a generic method declaration [nope, no generic methods]
    • Otherwise, if the namespace-or-type-name appears within a type declaration, then for each instance type T (§10.3.1), starting with the instance type of that type declaration and continuing with the instance type of each enclosing class or struct declaration (if any):
      • If K is zero and the declaration of T includes a type parameter with name I, then the namespace-or-type-name refers to that type parameter. [Nope]
      • Otherwise, if the namespace-or-type-name appears within the body of the type declaration, and T or any of its base types contain a nested accessible type having name I and K type parameters, then the namespace-or-type-name refers to that type constructed with the given type arguments. [Bingo!]
  • If the previous steps were unsuccessful then, for each namespace N, starting with the namespace in which the namespace-or-type-name occurs, continuing with each enclosing namespace (if any), and ending with the global namespace, the following steps are evaluated until an entity is located:
    • If K is zero and I is the name of a namespace in N, then... [Yes, that would succeed]

所以最后的要点是选择 Sparta 的原因class 如果第一个项目符号没有找到任何东西...但是当基类 Place定义接口(interface) Sparta ,它在我们考虑 Sparta 之前被发现类。

请注意,如果您创建嵌套类型 Place.Sparta一个类而不是一个接口(interface),它仍然编译并返回 false - 但编译器发出警告,因为它知道 Sparta 的一个实例永远不会是类 Place.Sparta 的实例.同样,如果您保留 Place.Sparta一个接口(interface),但使 Spartasealed ,你会收到警告,因为没有 Sparta实例可以实现接口(interface)。

关于c# - 这是斯巴达,还是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120947/

相关文章:

c# - 如何清理弱引用集合?

C# 静态属性锁定

c++ - C++ IDE Netbeans 或 Eclipse 不支持类继承吗?

Java Swing : Does the phrase "favor composition over inheritance" apply?

python - 为什么要继承对象类型

types - 类型断言后的 golang 类型转换

java - 什么是 AspectJ 中类型间声明的简短示例,它证明了该方法的有用性?

C# 对象大小开销

c# - 如何用 lambda 表达式决定应该处理哪个属性?

c++ - ClassName& 作为返回类型是什么意思?