来自不同 class 的 C# 调用方法,使用 'args' 作为参数

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

我正在编写一个 Discord Bot (Discord.net),我发现自己需要使用他们的 API 访问 google sheet 上的一些数据。因为我认为最好将这两个文件分开放在两个不同的 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

我尝试编写要传递到此处的参数 in these parentheses,例如“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();
            */
        }
    }
}

我已经根据 Google 给出的 quickstart 以我认为合理的方式对其进行了修改,但最终我仍然遇到相同的错误:

There is no argument given that corresponds to the required formal parameter 'args' of 'GoogleAPI.Sheets(string[])'

作为用户“David L”在评论中写道: 根据一般经验,如果您不使用参数,请将其删除。如果您的方法需要一个参数而您没有提供参数,C# 会通过抛出编译器错误来帮助强制执行此范例,这正是此处发生的情况。

这是我的错,因为在 API 实施期间我的印象完全相反。因此,我想始终以干净的代码为目标,保留我不会使用的东西是我的错。谢谢大卫!