2017-04-22 62 views
1

在您判断我发布ANOTHER NullReferenceException问题之前,请阅读我的代码。我一直在使用Google的NullReferenceException错误一段时间,并没有解释为什么这个特定的部分给我一个错误。e.After.VoiceChannel.Name Discord.NET - 找不到空错误

if (e.After.VoiceChannel.Name != null) 

我也看过Discord.NET的文档,但也没有任何结果。这是整个文件。

using Discord; 
using Discord.Commands; 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace DiscBot 
{ 
    class myBot 
    { 
     DiscordClient discord; 

     public myBot() 
     { 

      discord = new DiscordClient(x => 
      { 
       x.LogLevel = LogSeverity.Info; 
       x.LogHandler = Log; 
      }); 

      discord.UsingCommands(x => 
      { 
       x.PrefixChar = '~'; 
       x.AllowMentionPrefix = true; 
       x.HelpMode = HelpMode.Public; 
      }); 

      var commands = discord.GetService<CommandService>(); 

      commands.CreateCommand("greet") 
       .Description("Does a thing") 
       .Parameter("theGreeted", ParameterType.Unparsed) 
       .Do(async (e)=> 
       { 
        var msgtoRead = e.Channel.DownloadMessages(1); 

        await e.Channel.SendTTSMessage("Hello " + e.GetArg("theGreeted")); 
       }); 

      discord.UserUpdated += async (s, e) => { 
       var channel = e.Server.FindChannels("general", ChannelType.Text).FirstOrDefault(); 
       string usrnm = e.After.Name; 

       // This shouldn't get an error 
       // But when I run the code I 
       // get a Null Reference Exception 

       if (e.After.VoiceChannel.Name != null) 
       { 
        await channel.SendMessage(usrnm + " to " + e.After.VoiceChannel.Name); 
       } 
       else 
       { 

        await channel.SendMessage(usrnm + " exited"); 
       } 
      }; 


      discord.UserJoined += async (s, e) => 
      { 
       var channel = e.Server.FindChannels("mainbois", ChannelType.Text).FirstOrDefault(); 
       var user = e.User; 
       await channel.SendTTSMessage(string.Format("Another human has entered...")); 
      }; 

      discord.ExecuteAndWait(async() => 
      { 
       await discord.Connect("MYBOTTOKEN", TokenType.Bot); 
      }); 
     } 

     private void Log(object sender, LogMessageEventArgs e) 
     { 
     Console.WriteLine(e.Message); 
     } 
    } 
}  

任何帮助,非常感谢。提前致谢!

P.S.如果我在某个地方犯了一个简单的错误,请惩罚。 :P

+0

编辑:'e.After.VoiceChannel'为空。我不知道这个事件足以说明原因。 –

回答

1

发现我不能检查

if (e.After.VoiceChannel.Name != null) 

如果VoiceChannel为null。换句话说,我无法检查基于null的值(如果这是有意义的)。我的新代码看起来像

if (e.After.VoiceChannel != null) 

感谢任何花时间看我的代码的人。 :D