C# 分配一个具有特定名称的变量

标签 c# variables

我想将一个简单的类组合在一起,以从发送到我的应用程序的 HTTP 请求中挑选出 QueryString 变量。变量并不总是以相同的顺序排列,但它们始终存在。我想为我的类中的变量分配请求中相应变量的值,但我不知道该怎么做。

代码片段:

MyHTTPRequest ar = new MyHTTPRequest("GET /submit.php?variableOne=value&variableTwo=someothervalue HTTP/1.1"); // Leaving out the rest for now


class MyHTTPRequest
{
    public string variableOne;
    public string variableTwo;
    public string variableThree;

    private string[] properties = { "variableOne", "variableTwo", "variableThree" }; // I know they're not actually properties

    public MyHTTPRequest(string request)
    {
        string[] variablePars = request.Substring(16, request.Length - 24).Split('&'); // variablePars now contains "variableOne=value" & "variableTwo=someothervalue"

        foreach (string variablePar in variablePars)
        {
            if (properties.Contains(variablePar.Split('=')[0])) // variableOne, variableTwo, variableThree
            {
                // Assign the correct variable the value
                <???> = variablePar.Split('=')[1]; // I don't know how to pull this one off. variablePar.Split('=')[0] should contain the name of the variable.
            }
        }
    }

}

有什么意见吗?

我确定已经存在类似的问题,但我不知道用什么标题或标签。

最佳答案

使用 System.Web.HttpUtilityClass.ParseQueryString。它返回一个 NameValueCollection,就像您在 ASP.NET 中使用 Request.QueryString 获得的一样。

// assuming you can parse your string to get your string to this format.
string queryStringText = "variableOne=value&variableTwo=someothervalue";

NameValueCollection queryString = 
     HttpUtility.ParseQueryString(queryStringText);

string variable1 = queryString["variableOne"];
string variable2 = queryString["variableTwo"];

关于C# 分配一个具有特定名称的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3266677/

相关文章:

c# - 轻量级 C# 持久键值存储?

c# - 使用异步数据读取器

javascript - XPath 表达式中的变量

javascript - 这是全局变量吗?

php - 比较变量 foreach

c# - 有什么可以模拟静态接口(interface)的吗?

C# 字符串替换实际上并不替换字符串中的值

C++:变量与引用?

MySql 在 WHERE 中使用变量

c# - 如何使用重复器以编程方式添加未知数量的列,其中某些列是在运行时在 SQL 字符串中声明的?