【问题标题】:C# Call a function from another classC#调用另一个类的函数
【发布时间】:2019-07-08 23:41:38
【问题描述】:

我有 2 个类,一个包含函数,一个包含命令,我对此很陌生,不知道如何调用函数。

这是我要调用的函数

private async Task<long> GetMemberId(string members)
{
   long memberID = 0;

   HttpResponseMessage response = await client.GetAsync(StaticObjects.bungieBasePath 
                                  + $@"/GroupV2/Name/{memberID}/1/");
   if (response.IsSuccessStatusCode)
   {
      try
      {
         dynamic content = response.Content.ReadAsAsync<ExpandoObject>().Result;
         Debug.WriteLine(await response.Content.ReadAsStringAsync());
      }
      catch
      {
         throw new ArgumentException("The member could not be found.");
      }
   }
   else
   {
      throw new ArgumentException("An error occurred retrieving the members information.");
   }

   return memberID;
}

那么这是命令

[Command("invite")]
[RequireContext(ContextType.Guild, ErrorMessage = "This command is specific to a particular server so you must send it from a channel within that server")]
public async Task SendInviteAsync()
{
   await Context.Channel.TriggerTypingAsync(new RequestOptions() { Timeout = 30 });

   if (!Context.IsPrivate) await Context.Message.DeleteAsync();

   if (StaticObjects.CheckUserIsAdmin(Context))
   {
      //command to call the memberid function
   }
}

【问题讨论】:

  • 您需要从 'GetMemberId' 所在的任何类中调用它 - 这意味着您必须实例化该类的实例或让它成为静态方法。
  • 你明白class和它是一个实例的区别吗?通常,您应该以某种方式注入或创建class 的实例并调用指定的方法...
  • 它是private - 你不能在它的类之外调用它。设为internalpublic
  • 值得注意的是,D.Net 不鼓励这种模式;所有权限或条件检查都应移至前提条件。见Preconditions on Discord.Net Nightly Documentation。此外,RequestOptions.Timeout 并没有按照您的想法去做。如果您希望在执行任务期间让机器人进入打字状态,您应该使用IMessageChannel.EnterTypingState,同时将其包装在using 语句中。

标签: c# discord.net


【解决方案1】:

GetMemberId 是私有函数,只能在其类中使用。您需要将其公开,然后从其他类中调用它,如下所示:

if (StaticObjects.CheckUserIsAdmin(Context))
{
    var class = new firstClass();
    var memberId = class.GetMemberId(members);
}

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多