下面是一道面试题。我想出了一个解决方案,但我不确定它为什么有效。
问题:
在不修改 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
inMakeItReturnFalse()
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 formI<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 ofT
includes a type parameter with nameI
, 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 nameI
andK
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 andI
is the name of a namespace inN
, then... [Yes, that would succeed]
所以最后的要点是选择 Sparta
的原因class 如果第一个项目符号没有找到任何东西...但是当基类 Place
定义接口(interface) Sparta
,它在我们考虑 Sparta
之前被发现类。
请注意,如果您创建嵌套类型 Place.Sparta
一个类而不是一个接口(interface),它仍然编译并返回 false
- 但编译器发出警告,因为它知道 Sparta
的一个实例永远不会是类 Place.Sparta
的实例.同样,如果您保留 Place.Sparta
一个接口(interface),但使 Sparta
类 sealed
,你会收到警告,因为没有 Sparta
实例可以实现接口(interface)。
关于c# - 这是斯巴达,还是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120947/