[英]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.