C#中的global关键字

global关键字,就是字面的意思,全局。

其实有些时候会犯一些错误,就是类名取了一个跟系统类名雷同的情况,其实这是设计上的失误,但是会出现一个情况就是没改了,那么global关键字就起到了作用。

如下代码:

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace globalFunc
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 System sys = new System();
13 global::System.Console.WriteLine("global.");
14 global::System.Console.ReadKey();
15 }
16 }
17 public class System { }
18 }

虽然using了一个System命名空间,但是下面还有一个public class System{ ... }类,这样的话,如果直接使用System.Console.WriteLine是会报错的,因为会找到就近的System类,那么这个System类里面没有Console。所以如果需要使用的话,就需要像上面一样,使用global::System.Console.WriteLine,因为使用global标记的类会从全局开始寻找,我的理解就是会从最外面逐渐向内部寻找System类。

 高手无视,高手无视。

http://luacloud.com/2011/csharp-global.html

原文地址:https://www.cnblogs.com/luacloud/p/2268725.html