【问题标题】:using methods from another class without needing to use the class name使用另一个类的方法而不需要使用类名
【发布时间】:2020-05-20 11:48:31
【问题描述】:

您可以在 c# 文档中找到

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

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

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

我正在尝试将此应用到我的代码中,这样我就可以在另一个类的帮助器类 HelperClass 中使用方法,而无需使用类名 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()

我已经看到一些使用这个的教程代码,但我还没有发现我缺少什么......

【问题讨论】:

    标签: c# namespaces


    【解决方案1】:

    您需要添加以下内容:

    using static Sample.Helpers.HelperClass;
    

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

    更多关于using static directives的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 2019-07-04
      相关资源
      最近更新 更多