2011-10-07 89 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