. 运算符
点运算符 (.) 用于成员访问。点运算符指定类型或命名空间的成员。例如,点运算符用于访问 .NET Framework 类库中的特定方法:
C# | |
---|---|
// The class Console in namespace System: System.Console.WriteLine("hello"); |
本在线速查手册由www.w▇3▇x▇u▇e.com提供,请勿盗用!
例如,请考虑以下类:
C# | |
---|---|
class Simple { public int a; public void b() { } } |
本在线速查手册由www.w▇3▇x▇u▇e.com提供,请勿盗用!
C# | |
---|---|
Simple s = new Simple(); |
本在线速查手册由www.w▇3▇x▇u▇e.com提供,请勿盗用!
变量 s 有两个成员 a 和 b;若要访问这两个成员,请使用点运算符:
C# | |
---|---|
s.a = 6; // assign to field a; s.b(); // invoke member function b; |
本在线速查手册由www.w▇3▇x▇u▇e.com提供,请勿盗用!
点还用于构造限定名,即指定其所属的命名空间或接口的名称。
C# | |
---|---|
// The class Console in namespace System: System.Console.WriteLine("hello"); |
本在线速查手册由www.w▇3▇x▇u▇e.com提供,请勿盗用!
using 指令使某些名称限定可选:
C# | |
---|---|
namespace ExampleNS { using System; class C { void M() { System.Console.WriteLine("hello"); Console.WriteLine("hello"); // Same as previous line. } } } |
本在线速查手册由www.w▇3▇x▇u▇e.com提供,请勿盗用!
但是当某一标识符不确定时,必须限定它:
C# | |
---|---|
namespace Example2 { class Console { public static void WriteLine(string s){} } } namespace Example1 { using System; using Example2; class C { void M() { // Console.WriteLine("hello"); // Compiler error. Ambiguous reference. System.Console.WriteLine("hello"); //OK Example2.Console.WriteLine("hello"); //OK } } } |
本在线速查手册由www.w▇3▇x▇u▇e.com提供,请勿盗用!