Can I import a static class as a namespace to call

2019-04-20 05:11发布

问题:

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");
    }
}