[英]C# Language Question: priority of matching
我正在阅读“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,在类型上下文中用于指代 class A。
我对 class A 的可见性很好。但是,在这里( Type t = typeof(A)
) class A
前面是字符串A
。 那么,匹配/选择可能的“A”的“优先级”或“顺序”是什么?
没有冲突。 typeof
仅适用于 class 名称。 要获取 object 实例的类型,请使用.GetType()
。
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
在表达式上下文中,局部变量优先于 class。
当使用类型上下文时:
typeof(A)
A a =...
new
关键字之后: new A()
只考虑类型。 由于在那种情况下A
引用一个变量会导致无效的语法,它清楚地表明该类型是有意义的,因此规范允许它。
规则有点烦人的一种情况是,当您想引用 class 的 static 成员时。 例如A.CallStaticMethod()
。 在这里,您有一个表达式上下文,它指的是变量A
而不是 class A
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.