簡體   English   中英

使用來自另一個 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 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 的HelperClass成員,而無需使用 class 名稱限定它們。

有關using static指令的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM