简体   繁体   中英

C# Language Question: priority of matching

I'm reading book "C# Language", and hit this example from Page 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.

I'm fine with the visibility of class A. However, here ( Type t = typeof(A) ) class A preceded string A . So, what is the "priority" or "sequence" of matching/choosing a possible "A"?

There's no conflict. typeof only works on class names. To get the Type of an object instance, you use .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 . In the expression context the local variable takes precedence over the class.

When a type context is used:

  • Inside typeof(A)
  • When declaring a variable A a =...
  • After the new keyword: 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.

One case where the rule is a bit annoying is when you want to refer to a static member of the class. For example A.CallStaticMethod() . Here you have an expression context and it refers to the variable A and not the class A .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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