【问题标题】:Setting a classes' properties from NameValueCollection从 NameValueCollection 设置类的属性
【发布时间】:2011-03-14 19:59:33
【问题描述】:

我在一个页面上加密我的整个查询字符串,然后在另一个页面上解密它。我正在使用 HttpUtility.ParseQueryString 获取所有值的 NameValueCollection。

现在,我有一个属性与查询字符串变量名匹配的类。我正在努力如何从查询字符串中设置属性的值。

这是我正在编写的代码:

        NameValueCollection col = HttpUtility.ParseQueryString(decodedString);
        ConfirmationPage cp = new ConfirmationPage();

        for(int i = 0; i < col.Count; i++)
        {
            Type type = typeof(ConfirmationPage);
            FieldInfo fi = type.GetField(col.GetKey(i));               

        }

我看到了通过反射检索值的示例 - 但我想获取对 ConfirmationPage 类属性的引用并在循环中使用它的值设置它 - col.Get(i)。

【问题讨论】:

    标签: c# asp.net reflection


    【解决方案1】:

    我可能会另辟蹊径并找到属性(或使用 GetFields() 的字段) 并在查询参数中查找它们,而不是遍历查询参数。然后,您可以使用 PropertyInfo 对象上的 SetValue 方法来设置 ConfirmationPage 上的属性值。

    var col = HttpUtility.ParseQueryString(decodedString);
    var cp = new ConfirmationPage();
    
    foreach (var prop in typeof(ConfirmationPage).GetProperties())
    {
        var queryParam = col[prop.Name];
        if (queryParam != null)
        {
             prop.SetValue(cp,queryParam,null);
        }
    }
    

    【讨论】:

    • var prop 抛出错误“必须初始化隐式类型的局部变量” - prop 实际上应该是什么对象?
    • foreach 循环 - 不是 for 循环。
    【解决方案2】:

    试试:

    typeof(ConfirmationPage).GetProperty(col.GetKey(i))
                            .SetValue(cp, col.Get(i), null);
    

    【讨论】:

    • 在启用 AJAX 的页面上要小心。当您指定不希望缓存响应时,Javascript 框架通常会添加额外的参数(如时间戳)。这会破坏此代码,因为您将寻找与类上的属性不对应的参数,因此在未找到该属性时会得到 NullReferenceException。
    猜你喜欢
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2023-03-17
    • 2018-11-05
    • 2015-03-10
    • 1970-01-01
    相关资源
    最近更新 更多