C# 将字符串转换为常量字符串

C# Convert string to const string

我正在使用 tcp 服务器和客户端,我需要将用户输入 (Console.ReadLine();) 转换为现有的 const 字符串。代码如下:

    const int PORT_NO = 8080;
    const string SERVER_IP = "127.0.0.1";
    public static void MainClient()
    {

        SERVER_IP = Console.ReadLine(); //I need help here :(

        //The boring stuff
    }

顺便说一句:tcp 代码需要 const 字符串,所以我不能只删除它并使用常规字符串值

const cannot be modified 标记的常量。

You use the const keyword to declare a constant field or a constant local. Constant fields and locals aren't variables and may not be modified.

删除 const 关键字以使您的字段成为变量并添加 static 代替,否则您无法在静态 MainClient 方法中访问该字段。

您不能为在编译时为 const 的字段赋值。相反,您可以将该字段设为只读,并在 class 构造函数中分配您从控制台读取的值。如果我正确理解您的问题,那将是我的方法。类似于:

const int PORT_NO = 8080;
readonly string SERVER_IP = "127.0.0.1";
public static void MainClient()
{

    SERVER_IP = Console.ReadLine(); //I need help here :(

    //The boring stuff
}

希望对您有所帮助。

已修复!我没有读到错误。它可以是常规字符串值,但函数不能是静态的。这是最终代码

const int PORT_NO = 8080;
string SERVER_IP = "127.0.0.1";
public void MainClient()
{

    SERVER_IP = Console.ReadLine(); //I need help here :(

    //The boring stuff
}