命令行变量/字符串

时间:2012-10-27 11:10:51

标签: c#

嘿伙计们,我需要帮助我正在制作的程序,我已经找到了一切但只有一个。

我的代码看起来像这样,但我已经缩短了一点......

public static void mainvoid()
{
    string line = Console.ReadLine().ToLower();
    if (line == "restart")
    {
        Console.Clear();
        Main();
    }
    if (line == "enter a value: ")
    {
        string value = console.ReadLine();
        console.writeline("Your value is {0}", value);
        mainvoid();
    }
    if (line == "my name")
    {
        Console.WriteLine("Your name is {0}",     ConsoleApplication1.Properties.Settings.Default.name);
        mainvoid();
    }

我希望我的程序能够获取一个命令(我已经做过的女巫......),其中一些人在他们之后有值/字符串。 顺便说一句,我正在使用c#2010 我希望我的命令看起来像这样

  

我的名字是丹尼尔   所以字符串/值=丹尼尔   或
     名字=比利   所以字符串/值=比利

所以我希望它通过console.readline();并选择它正在更改名称,之后将更改为名称。

但是我不知道如何将最后一位用于我也可以使用的值/字符串... 如果你可以帮助我,请发表评论:)

3 个答案:

答案 0 :(得分:1)

您可能需要提出自己的语法。

例如,我选择了如下语法

<Command Name>:Parameters    
ChangeName:Daniel

然后有一个枚举来定义你的命令

enum Command
{
      ChangeName
} 

//现在我们可以解析命令并采取必要的操作

//Split the string
String[] inputs= Console.ReadLine().Split(":");//"ChangeName:Bob"

//Generate the enumeration type from the input command
var cmd = (Command) Enum.Parse(typeof(Command), inputs[0] , false);

if(cmd == Command.ChangeName)
{
//Process the parameters in inputs[1]
}

答案 1 :(得分:0)

如果您不想通过Console.ReadLine()选择命令,请选择Console.ReadKey(true)。您的文字不会改变。

以下是示例:

ConsoleKeyInfo ck = Console.ReadKey(true);
if(ck.Key == Keys.Space){
//do something
}

我不太了解你,但我会猜测:)

如果您想要检索名称,可以这样写:

Console.Write("Your name is ");
string name = Console.ReadLine();

答案 2 :(得分:0)

我可以看到这里有两个问题,一个是从“my name is xyz”命令中提取人名,另一个是在程序中保存该值。

由于你构造mainmethod的方式,以及它调用自身的事实(这称为递归),它不能共享从一个调用到下一个调用的任何变量。这使得无法存储人名。您可以通过在mainmethod

中创建循环来消除递归
static public void Main()
{
    string currentLine;

    do
    {
        currentLine = Console.ReadLine();
    }
    while (!currentLine.Equals("exit"))
}

这将持续允许用户输入命令,当用户进入“退出”时程序将终止。

现在解决存储用户名的问题,你可以简单地删除句子中的“我的名字是”部分来获取用户名...

static public void Main()
{
    string username = "Matthew";

    string currentLine;

    do
    {
        currentLine = Console.ReadLine();

        if (currentLine.Equals("restart"))
        {
            Console.Clear();
        }

        if (currentLine.StartsWith("my name is"))
        {
            username = currentLine.Replace("my name is ", "");
        }

        if (currentLine.Equals("my name"))
        {
            Console.WriteLine("Your name is {0}", username);
        }
    }
    while (!currentLine.Equals("exit"))
}

我希望能让你感动!

相关问题