自/至对象转换查询字符串 [英] Convert querystring from/to object

查看:125
本文介绍了自/至对象转换查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个(简体)类:

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.

我知道,这是pretty太大的ModelBinder的做什么,但我没有在我的处境控制器上下文(在一个线程中的一些深埋类运行)。

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).

那么,有没有一个对象转换在查询字符串和背部而无需控制器上下文的简单方法?

这将是巨大的使用modelbinding,但我不知道怎么办。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆