e.After.VoiceChannel.Name Discord.NET - 无法找出null错误

时间:2017-04-22 02:00:05

标签: c# nullreferenceexception discord discord.net

在您判断我发布另一个NullReferenceException问题之前,请先阅读我的代码。我一直在谷歌搜索NullReferenceException错误一段时间了,它没有解释为什么这个特定部分给我一个错误。

    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

1 个答案:

答案 0 :(得分:1)

发现我无法检查

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

如果VoiceChannel为空。换句话说,我无法根据null检查一个值(如果这有意义的话)。我的新代码看起来像

if (e.After.VoiceChannel != null)

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