Can I import a static class as a namespace to call

2019-04-20 05:07发布

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#?

3条回答
该账号已被封号
2楼-- · 2019-04-20 05:52

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

查看更多
贪生不怕死
3楼-- · 2019-04-20 06:09

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

查看更多
再贱就再见
4楼-- · 2019-04-20 06:11

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");
    }
}
查看更多
登录 后发表回答