Static Using Statements 这怎解释?看名称不解。
如果改成 Using Statements for Static 会不会比较适当一点?
这又是一个 C# 6.0 的语法糖(syntactic sugar)
看一下例子:(从 MSDN 上找来的)
如果改成 Using Statements for Static 会不会比较适当一点?
这又是一个 C# 6.0 的语法糖(syntactic sugar)
看一下例子:(从 MSDN 上找来的)
using System;
using System.Console;
public class Program
{
private static void Main()
{
ConsoleColor textColor = ForegroundColor;
try
{
ForegroundColor = ConsoleColor.Red;
WriteLine("Hello, my name is Inigo Montoya... Who are you?: ");
ForegroundColor = ConsoleColor.Green;
string name = ReadLine(); // Respond: No one of consequence
ForegroundColor = ConsoleColor.Red;
WriteLine("I must know.");
ForegroundColor = ConsoleColor.Green;
WriteLine("Get used to disappointment");
}
finally
{
ForegroundColor = textColor;
}
}
}
重点在於一开始的:
using System.Console;
在以前的版本,using 主要用於
1. using [namespace]
2. using [alias name] = [Fully Qualified Type Name]
第一种是用来引用该命名空间下的各种类型
第二种是用来替某个类型取别名
当然还有 using(var x = new xxx){} 这个不在此讨论。
这个 using System.Console;
就是 Static Using Statement
一开始引用之后,后面的语法就可以:
就是 Static Using Statement
一开始引用之后,后面的语法就可以:
WriteLine("Hello, my name is Inigo Montoya... Who are you?: ");
而不用再写成
Console.WriteLine("Hello, my name is Inigo Montoya... Who are you?: ");
所以像 System.Console, System.Math 这些有许多静态方法的类,就蛮适合的。
除了这个之外,另外一个效果是:
这种方式 只会引入指定类的扩展方法 (Extension Method),而不是引入某命名空间下的全部扩展方法。这个蛮不错的。