C# 设置一个类';NameValueCollection中的属性
我在一个页面上加密整个查询字符串,然后在另一个页面上解密它。我使用HttpUtility.ParseQueryString获取所有值的NameValueCollection 现在,我有一个类,它的属性与查询字符串变量名匹配。我正在努力从查询字符串中设置属性的值 以下是我正在编写的代码:C# 设置一个类';NameValueCollection中的属性,c#,asp.net,reflection,C#,Asp.net,Reflection,我在一个页面上加密整个查询字符串,然后在另一个页面上解密它。我使用HttpUtility.ParseQueryString获取所有值的NameValueCollection 现在,我有一个类,它的属性与查询字符串变量名匹配。我正在努力从查询字符串中设置属性的值 以下是我正在编写的代码: NameValueCollection col = HttpUtility.ParseQueryString(decodedString); ConfirmationPage cp
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));
}
NameValueCollection col=HttpUtility.ParseQueryString(decodedString);
ConfirmationPage cp=新的ConfirmationPage();
for(int i=0;i
我看到了通过反射检索值的示例,但我想获取对ConfirmationPage类属性的引用,并将其设置为循环中的值-col.get(I)。尝试:
typeof(ConfirmationPage).GetProperty(col.GetKey(i))
.SetValue(cp, col.Get(i), null);
我可能会走另一条路,找到属性(或使用GetFields()的字段) 并在查询参数中查找它们,而不是迭代查询参数。然后,可以使用PropertyInfo对象上的SetValue方法在确认页面上设置属性的值
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);
}
}
使用支持AJAX的页面时要小心。当您指定不需要缓存响应时,Javascript框架通常会添加额外的参数(如时间戳)。这将破坏此代码,因为您将查找与类上的属性不对应的参数,因此在找不到该属性时将获得NullReferenceException。var prop抛出错误“隐式类型的局部变量必须初始化”-道具实际上应该是什么对象?每个循环的目的-不是循环。