2011-10-07 93 views
42

C#是否具有像Java的靜態導入功能?靜態導入c#

所以不是寫代碼就像

FileHelper.ExtractSimpleFileName(file) 

我可以寫

ExtractSimpleFileName(file) 

和編譯器會知道我的意思是,從FileHelper方法。

+0

的[?是否有可能在一個靜態類引用的方法,而不引用類]可能的複製(http://stackoverflow.com/questions/30671769/is-it-it-to-reference-a-method-in-a-static-class-without-referencing-the-c) –

回答

64

與C#6.0開始,這是可能的:

using static FileHelper; 

// in a member 
ExtractSimpleFileName(file) 

然而,C#以前的版本不具有靜態進口。

您可以使用類型的別名關閉。

using FH = namespace.FileHelper; 

// in a member 
FH.ExtractSimpleFileName(file) 

另外,在類型更改爲extension method靜態方法 - 那麼你就能夠稱呼其爲:

var value = file.ExtractSimpleFileName(); 
12

不,這樣的功能在C#中不存在。你需要指定靜態方法所屬的類,除非你已經在這個類的一個方法內。

在C#中雖然你有extension methods這種模仿這種。

4

時間遊行上......它看起來像C#可能會靜在下一版本中導入,請參閱http://msdn.microsoft.com/en-us/magazine/dn683793.aspx預覽。

using System; 
using System.Console; // using the Console class here 

public class Program 
{ 
    public static void Main() 
    { 
     // Console.WriteLine is called here 
     WriteLine("Hello world!"); 
    } 
} 

official documentation爲 '羅斯林' C#編譯器列出的功能爲 '完成'

+0

Jack be Nimble,Jack be Quick ... with C#static usess! 我無法表達我對這個功能的興奮程度。我一直熱切地等待這種表達能力進入語言多年,但從未想到我會看到這一天。 –

2

C#6.0下羅斯林平臺supports Static import。它需要聲明,如:

using static System.Console; 

所以代碼可能看起來像:

using static System.Console; 
namespace TestApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      WriteLine("My test message"); 
     } 
    } 
} 

較早的計劃版本的C#6.0有靜態導入沒有static關鍵字。

在C#中的其他新功能6.0參見:New Language Features in C# 6