我打電話給一個webservice,返回四個自定義類之一的數組。 所有類都具有相同的內容 - 一個名爲Description的字符串和另一個名爲Value的字符串。 我想寫一個可以接受四個類中的任何一個的方法,並將其內容放入下拉列表的數據源中。從一個類轉換爲另一個
有沒有辦法將未知的組合類轉換爲具有相同內容的指定類?或者將內容刪除?
或者我將不得不用不同的數據類型來編寫四個相同的函數嗎?
編輯:添加代碼
myDropDown.DataSource = CreateDataSource(myWebServiceResponse.Items);
myDropDown.DataTextField = "DescriptionField";
myDropDown.DataValueField = "ValueField";
// Bind the data to the control.
myDropDown.DataBind();
...
public ICollection CreateDataSource(MasterData[] colData)
{
// Create a table to store data for the DropDownList control.
DataTable dt = new DataTable();
// Define the columns of the table.
dt.Columns.Add(new DataColumn("DescriptionField", typeof(String)));
dt.Columns.Add(new DataColumn("ValueField", typeof(String)));
// Populate the table
foreach (sapMasterData objItem in colData)
{
dt.Rows.Add(CreateRow(objItem, dt));
}
// Create a DataView from the DataTable to act as the data source
// for the DropDownList control.
DataView dv = new DataView(dt);
return dv;
}
DataRow CreateRow(MasterData objDataItem, DataTable dt)
{
// Create a DataRow using the DataTable defined in the
// CreateDataSource method.
DataRow dr = dt.NewRow();
dr[0] = objDataItem.Description;
dr[1] = objDataItem.Value;
return dr;
}
public class MasterData
{
public string Value;
public string Description;
}
這將是有益的,如果你提供一些代碼秒。 – 2013-04-23 06:15:42
你可以使用'動態'。 – 2013-04-23 06:16:48
你可以在所有類上放置一個接口並使用它。或者你可以使用AutoMapper – Brian 2013-04-23 06:17:53