从/到对象转换查询字符串 [英] Convert querystring from/to object
问题描述
我有这个(简化的)类:
I have this (simplified) class:
public class StarBuildParams
{
public int BaseNo { get; set; }
public int Width { get; set; }
}
我必须将它的实例转换为这样的查询字符串:
And I have to transform instances of it to a querystring like this:
"BaseNo=5&Width=100"
此外,我必须将这样的查询字符串转换回该类的对象中.
Additionally I have to transform such a querystring back in an object of that class.
我知道这几乎是模型绑定器的作用,但在我的情况下我没有控制器上下文(一些在线程中运行的深埋类).
I know that this is pretty much what a modelbinder does, but I don't have the controller context in my situation (some deep buried class running in a thread).
那么,是否有一种简单的方法可以在没有控制器上下文的情况下在查询字符串中转换对象并返回?
使用模型绑定会很棒,但我不知道如何.
It would be great to use the modelbinding but I don't know how.
推荐答案
你可以使用反射,像这样:
You can use reflection, something like this:
public T GetFromQueryString<T>() where T : new(){
var obj = new T();
var properties = typeof(T).GetProperties();
foreach(var property in properties){
var valueAsString = HttpContext.Current.Request.QueryString[property.PropertyName];
var value = Parse( valueAsString, property.PropertyType);
if(value == null)
continue;
property.SetValue(obj, value, null);
}
return obj;
}
您需要实现 Parse 方法,只需使用 int.Parse、decimal.Parse、DateTime.Parse 等
You'll need to implement the Parse method, just using int.Parse, decimal.Parse, DateTime.Parse, etc.
这篇关于从/到对象转换查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!