静态导入c#(static imports in c#)

编程入门 行业动态 更新时间:2024-10-28 10:26:57
静态导入c#(static imports in c#)

C#是否具有Java的静态导入功能?

所以代替编写代码

FileHelper.ExtractSimpleFileName(file)

我可以写

ExtractSimpleFileName(file)

编译器会知道我的意思是FileHelper的方法。

Does C# has feature like Java's static imports?

so instead of writing code like

FileHelper.ExtractSimpleFileName(file)

I could write

ExtractSimpleFileName(file)

and compiler would know that I mean method from FileHelper.

最满意答案

从C#6.0开始,这是可能的:

using static FileHelper; // in a member ExtractSimpleFileName(file)

但是,以前版本的C#没有静态导入。

您可以使用该类型的别名来获取关闭。

using FH = namespace.FileHelper; // in a member FH.ExtractSimpleFileName(file)

或者,将静态方法更改为类型的扩展方法 - 然后可以将其称为:

var value = file.ExtractSimpleFileName();

Starting with C# 6.0, this is possible:

using static FileHelper; // in a member ExtractSimpleFileName(file)

However, previous versions of C# do not have static imports.

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 method on the type - you would then be able to call it as:

var value = file.ExtractSimpleFileName();

更多推荐

本文发布于:2023-08-07 05:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1461166.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   static   imports

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!