2010-08-30 39 views
1

MyObject myobject = new MyObject(); myobject.name =「Test」; myobject.address =「test」; myobject.contactno = 1234; string 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 

誰能告訴我,我究竟做錯了什麼?

回答

1

在這種情況下,「myobject」自動調用其ToString()方法,該方法以字符串形式返回對象的類型。

您需要挑選每個屬性並將其與查詢字符串的值一起添加到查詢字符串中。你可以爲此使用PropertyInfo類。

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

的的GetProperties()方法被重載,並且可以與的BindingFlags被調用,使得僅定義的屬性返回(如BindingFlags.Public以僅返回公共屬性)。請參閱:http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx

1

我會推薦定義如何將MyObject變成查詢字符串值。在知道如何爲其所有值設置屬性的對象上創建一個方法。

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

然後不添加myObject,而是添加myObject.ToQueryString()。

0

這裏是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; 
    } 
相關問題