我正在阅读“C#语言”一书,并从第123-124页
点击此示例块内名称的含义可能因使用名称的上下文而异。
在示例中
using System;
class A { }
class Test
{
static void Main()
{
string A = "hello, world";
string s = A; // Expression context
Type t = typeof(A); // Type context
Console.WriteLine(s); // Writes "hello, world"
Console.WriteLine(t); // Writes "A"
}
}
在表达式上下文中使用名称A来引用局部变量A和类型 上下文指的是A类。
我对A类的可见性很好。但是,这里(Type t = typeof(A)
)class A
位于字符串A
之前。
那么,匹配/选择可能的“A”的“优先级”或“顺序”是什么?
答案 0 :(得分:4)
没有冲突。 typeof
仅适用于类名。要获取对象实例的类型,请使用.GetType()
。
答案 1 :(得分:1)
string A = "hello, world";
string s = A; // Expression context
A a=new A();
Type t = typeof(A); // Type context
Console.WriteLine(s); // Writes "hello, world"
Console.WriteLine(t); // Writes "A"
这里我们看到一个表达式上下文的例子:string s = A
。在表达式上下文中,局部变量优先于类。
使用类型上下文时:
typeof(A)
A a = ...
new
关键字后:new A()
仅考虑类型。因为在该上下文中A
引用一个变量会导致语法无效,所以明确表示该类型是指的,因此规范允许它。
规则有点烦人的一种情况是当你想引用类的静态成员时。例如A.CallStaticMethod()
。这里有一个表达式上下文,它引用变量A
而不是类A
。