【问题标题】:How to check if an object exists in a class [duplicate]如何检查类中是否存在对象[重复]
【发布时间】:2019-11-17 06:11:29
【问题描述】:

这是我当前的代码;

        static void Adonis()
        {
            Console.Write("adonis@" + prefix + "# ");
            string adonisInput = Console.ReadLine();
            CmdCheck(adonisInput);
        }

        static void CmdCheck(string arg)
        {
            if (arg.Contains("use"))
            {
                string str = arg;
                string[] tokens = str.Split(' ');
                string chosenExploit = tokens[1];
                if (chosenExploit == "pscan")
                {
                    p(pscan.print());
                    Adonis();
                }
                if (chosenExploit == "ping")
                {
                    //code
                }
                if (!(chosenExploit is module)) // this line keeps getting the error
                {
                    p("Invalid Syntax: '" + arg + "', 'use <arg>'; missing argument.");
                    Adonis();
                }
            }
            Console.WriteLine("Unknown command, '" + arg + "', type 'help' for more commands.");
            Adonis();
        }

让我在我的倡议中加入一些背景知识。

我有两个名为“pscan”和“ping”的对象。如果他们想使用 pscan 或 ping,他们应该能够输入“使用 pscan”或“使用 ping”。我通过找到“使用”和输入之间的分割来做到这一点,然后我阅读了以下文本。这可能是“pscan”或“ping”。

我想进行一些错误处理,所以我想看看,如果有人输入了“use”、“use”之类的东西,甚至拼错了“use pscna”之类的东西会怎样。我希望它读取 "pscna" 或 null ("") 并返回它并告诉用户他们缺少参数并且它是无效的语法。

我不断收到的错误是“索引超出了数组的范围”。

【问题讨论】:

  • if (!(chosenExploit is module)) 行不应产生此特定错误。此行可能会引发此错误:string chosenExploit = tokens[1]; - 特别是,如果用户输入的值中没有空格。

标签: c# class object methods


【解决方案1】:
string chosenExploit = tokens[1];

这部分只有在用户在“use”之后输入了一些东西时才有效,否则你的数组将只是一个“use”的单词,所以我建议你首先检查数组的长度是否为 1看看有没有争论。

【讨论】:

    猜你喜欢
    • 2015-05-26
    • 2021-08-06
    • 2022-01-16
    • 2013-03-28
    • 2020-05-08
    • 2018-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多