java C#中的静态导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7692826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
static imports in c#
提问by IAdapter
Does C# has feature like Java's static imports?
C# 是否具有像 Java 的静态导入这样的功能?
so instead of writing code like
所以而不是像这样写代码
FileHelper.ExtractSimpleFileName(file)
I could write
我可以写
ExtractSimpleFileName(file)
and compiler would know that I mean method from FileHelper.
编译器会知道我的意思是来自 FileHelper 的方法。
回答by Oded
Starting with C# 6.0, this is possible:
从 C# 6.0 开始,这是可能的:
using static FileHelper;
// in a member
ExtractSimpleFileName(file)
However, previous versions of C# do not have static imports.
但是,以前版本的 C# 没有静态导入。
You can get close with an alias for the type.
您可以使用该类型的别名。
using FH = namespace.FileHelper;
// in a member
FH.ExtractSimpleFileName(file)
Alternatively, change the static method to an extension methodon the type - you would then be able to call it as:
或者,将静态方法更改为类型上的扩展方法- 然后您可以将其调用为:
var value = file.ExtractSimpleFileName();
回答by Darin Dimitrov
No, such feature doesn't exist in C#. You need to specify the class that the static method belongs to unless you are already inside a method of this same class.
不,C# 中不存在此类功能。您需要指定静态方法所属的类,除非您已经在同一个类的方法中。
In C# though you have extension methodswhich kind of mimic this.
在 C# 中,虽然你有扩展方法,可以模仿这一点。
回答by Michiel van Oosterhout
Time marches on... it looks like C# might get static imports in the next version, see http://msdn.microsoft.com/en-us/magazine/dn683793.aspxfor a preview.
时间在流逝……看起来 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!");
}
}
The official documentationfor the 'Roslyn' C# compiler lists the feature as 'done'
“Roslyn”C# 编译器的官方文档将该功能列为“完成”
回答by Habib
C# 6.0 under Roslyn Platform supports Static import. It requires statement like:
Roslyn 平台下的 C# 6.0支持静态导入。它需要像这样的语句:
using static System.Console;
so the code might look like:
所以代码可能如下所示:
using static System.Console;
namespace TestApplication
{
class Program
{
static void Main(string[] args)
{
WriteLine("My test message");
}
}
}
The earlier planned version for C# 6.0 had static import withoutstatic
keyword.
C# 6.0 的早期计划版本具有没有static
关键字的静态导入。
For other new features in C# 6.0 see: New Language Features in C# 6
有关 C# 6.0 中的其他新功能,请参阅:C# 6 中的新语言功能