使用另一个 class 的方法而不需要使用 class 名称

using methods from another class without needing to use the class name

如您在 c# 文档中所见

System.Console.WriteLine("Hello World!");

System 是一个命名空间,Console 是该命名空间中的一个 class。可以使用 using 关键字,这样就不需要完整的名称,如下例所示:

using System;
Console.WriteLine("Hello");
Console.WriteLine("World!");

我正在尝试将它应用到我的代码中,这样我就可以在另一个 class 的助手 class HelperClass 中使用一个方法,而无需使用 class 姓名 HelperClass.HelperMethod();

像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sample.Helpers
{
    public static class HelperClass
    {
        public static void HelperMethod()
        {
            // Do something here
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sample.Helpers;


    namespace Sample
    {
        class Program
        {
            static void Main(string[] args)
            {
                // call HelperMethod
                HelperMethod();
            }
        }
    }

很遗憾,HelperMethod() 没有被编译器找到

我看过一些使用它的教程代码,但我还没有找到我缺少的东西...

您需要添加以下内容:

using static Sample.Helpers.HelperClass;

这将允许您使用 HelperClass 的静态成员,而无需使用 class 名称限定它们。

有关 using static directives 的更多信息。