简体   繁体   English

C# 语言问题:匹配优先级

[英]C# Language Question: priority of matching

I'm reading book "C# Language", and hit this example from Page 123-124:我正在阅读“C#语言”一书,并从第 123-124 页点击了这个示例:

The meaning of a name within a block may differ based on the context in which the name is used.块中名称的含义可能会根据使用名称的上下文而有所不同。

In the example在示例中

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"
  }
}  

the name A is used in an expression context to refer to the local variable A and in a type context to refer to the class A.名称 A 在表达式上下文中用于指代局部变量 A,在类型上下文中用于指代 class A。

I'm fine with the visibility of class A. However, here ( Type t = typeof(A) ) class A preceded string A .我对 class A 的可见性很好。但是,在这里( Type t = typeof(A) ) class A前面是字符串A So, what is the "priority" or "sequence" of matching/choosing a possible "A"?那么,匹配/选择可能的“A”的“优先级”或“顺序”是什么?

There's no conflict.没有冲突。 typeof only works on class names. typeof仅适用于 class 名称。 To get the Type of an object instance, you use .GetType() .要获取 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"

Here we see one example of an expression context: string s = A .这里我们看到一个表达式上下文的例子: string s = A In the expression context the local variable takes precedence over the class.在表达式上下文中,局部变量优先于 class。

When a type context is used:当使用类型上下文时:

  • Inside typeof(A)内部typeof(A)
  • When declaring a variable A a =...当声明一个变量A a =...
  • After the new keyword: new A()new关键字之后: new A()

Only the type is considered.只考虑类型。 Since in that context A referring to a variable would result in invalid grammar its clear that the type is meant and thus the specification allows it.由于在那种情况下A引用一个变量会导致无效的语法,它清楚地表明该类型是有意义的,因此规范允许它。

One case where the rule is a bit annoying is when you want to refer to a static member of the class.规则有点烦人的一种情况是,当您想引用 class 的 static 成员时。 For example A.CallStaticMethod() .例如A.CallStaticMethod() Here you have an expression context and it refers to the variable A and not the class A .在这里,您有一个表达式上下文,它指的是变量A而不是 class A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM