簡體   English   中英

C# 從不同的 class 調用方法,以 'args' 作為參數

[英]C# call method from different class with 'args' as a parameter

我正在寫一個 Discord Bot (Discord.net),我發現自己需要使用他們的API訪問谷歌表上的一些數據。 因為我認為最好將這兩個實際分開在兩個不同的 class 文件中,我嘗試將 Google API 的Main方法調用到我的程序中(在將其重命名為“ Sheets ”之后),就像在我的Program.cs中這樣:

using Discord;
using Discord.WebSocket;
using System;
using System.IO;
using System.Threading.Tasks;

namespace WoM_Balance_Bot
{
    public class Program
    {
        public static void Main(string[] args)
        {
            GoogleAPI GSheet = new GoogleAPI();
            GSheet.Sheets();

            new Program().MainAsync().GetAwaiter().GetResult();
        }

        private DiscordSocketClient _client;

        public async Task MainAsync()
        {
            _client = new DiscordSocketClient();
            _client.MessageReceived += CommandHandler;
            _client.Log += Log;

            var token = File.ReadAllText("bot-token.txt");

            await _client.LoginAsync(TokenType.Bot, token);
            await _client.StartAsync();

            // Block this task until the program is closed.
            await Task.Delay(-1);
        }.......ecc

我嘗試編寫要在這些括號中傳遞的參數,例如“ string ”和“ args ”,但要么我的語法錯誤,要么我對確切傳遞的內容有一個非常錯誤的想法。

這是GoogleAPI.cs的實際內容,這是我創建的另一個 class 文件,它具有 Google Sheet API:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace WoM_Balance_Bot
{
    public class GoogleAPI
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json
        private static readonly string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };

        private static readonly string ApplicationName = "wombankrolls";

        public static void Sheets(string[] args)
        {
            UserCredential credential;

            Console.WriteLine("if you read this then it's good");

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define request parameters.
            String spreadsheetId = "16W56LWqt6wDaYAU5xNdTWCdaY_gkuQyl4CE1lPpUui4";
            String range = "Class Data!G163:I";
            SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);

            // Prints the names and majors of students in a sample spreadsheet:
            // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
            ValueRange response = request.Execute();
            IList<IList<Object>> values = response.Values;

            /*
            if (values != null && values.Count > 0)
            {
                Console.WriteLine("Name, Major");
                foreach (var row in values)
                {
                    // Print columns A and E, which correspond to indices 0 and 4.
                    Console.WriteLine("{0}, {1}", row[0], row[4]);
                }
            }
            else
            {
                Console.WriteLine("No data found.");
            }
            Console.Read();
            */
        }
    }
}

我已經從谷歌給出的快速入門中修改了它,我認為它是有道理的,但最終我仍然得到同樣的錯誤:

沒有給出與“GoogleAPI.Sheets(string[])”的所需形式參數“args”相對應的參數

正如用戶“ David L ”在評論中所寫:作為一般經驗法則,如果您不使用參數,請將其刪除。 C# 如果您的方法需要一個參數並且您沒有提供一個參數,則通過引發編譯器錯誤來幫助強制執行此范例,這正是這里發生的情況。

這是我的錯,因為在 API 實施期間,我的印象完全相反。 因此,我希望始終以干凈的代碼為目標,而保留我不會使用的東西是我的壞事。 謝謝大衛!

暫無
暫無

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

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