myObject myObject = new myObject(); myObject.name =“ test”; MyObject.Address =“ test”; MyObject.Contactno = 1234;字符串url =“http://www.myurl.com/key/1234?” + myObject; webrequest myRequest = webrequest.create(url); webresponse myResponse = myRequest.getResponse(); myResponse.close();

现在以上无法正常工作,但是如果我尝试以这种方式手动击中URL -

"http://www.myurl.com/Key/1234?name=Test&address=test&contactno=1234

谁能告诉我我在这里做错了什么?

有帮助吗?

解决方案

在这种情况下,“ myobject”会自动调用其toString()方法,该方法将对象的类型返回为字符串。

您需要选择每个属性,并将其添加到Querystring及其值。您可以将PropertyInfo类使用。

foreach (var propertyInfo in myobject.GetType().GetProperties())
{
     url += string.Format("&{0}={1}", propertyInfo.Name, propertyInfo.GetValue(myobject, null));
}

GetProperties()方法被超载,可以用bindingflags调用,以便仅返回定义的属性(例如bindingflags.publics,仅返回公共属性)。看: http://msdn.microsoft.com/en-us/library/kyaxd3x.aspx

其他提示

我建议定义如何将MyObject变成查询字符串值。在对象上制作一个方法,该方法知道如何为其所有值设置属性。

public string ToQueryString()
{
    string s = "name=" + this.name;
    s += "&address=" + this.address;
    s += "&contactno=" + this.contactno;
    return s
}

然后,不要添加myObject,而是添加myObject.toqueryString()。

这是我写的tostring方法 -

public override string ToString()
    {
        Type myobject = (typeof(MyObject));
        string url = string.Empty;
        int cnt = 0;
        foreach (var propertyInfo in myobject.GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            if (cnt == 0)
            {
                url += string.Format("{0}={1}", propertyInfo.Name, propertyInfo.GetValue(this, null));
                cnt++;
            }
            else
                url += string.Format("&{0}={1}", propertyInfo.Name, propertyInfo.GetValue(this, null));
        }
        return url;
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top