Can I import a static class as a namespace to call its methods without specifying the class name in C#?

☆樱花仙子☆ 提交于 2019-12-05 14:25:19

问题


I make extensive use of member functions of one specific static class. Specifying the class name every time I call it's methods looks nasty...

Can I import a static class as a namespace to call its methods without specifying the class name C#?


回答1:


If you mean import it such that it's methods are global, no.

You might want to look at extension methods though. They are static methods that, when their class's namespace is imported, show up as instance methods on the type of their first argument. See more here: http://msdn.microsoft.com/en-us/library/bb383977.aspx




回答2:


The feature you were looking for was added within C# 6.0

It's called "Using Static".

Here's the link for more explanations and examples: https://msdn.microsoft.com/en-us/magazine/dn879355.aspx




回答3:


Yes, you can. C# 6 introduced new construct - the using static directive lets you import all the static members of a type, so that you can use those members unqualified :

using static ClassName;

for instance:

using System;

using static System.Console;

class Program
{
    static void Main()
    {
        WriteLine("test");
    }
}


来源:https://stackoverflow.com/questions/6319226/can-i-import-a-static-class-as-a-namespace-to-call-its-methods-without-specifyin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!