我正在调用一个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;
}
答案 0 :(得分:3)
实际上DropDownList
控件要求您使用IEnumerable
作为数据源,然后您可以指定DataTextField
和DataValueField
:
dropDownList.DataSource = some_Array_You_Retrieved_From_Your_Web_Service;
dropDownList.DataValueField = "Value";
dropDownList.DataTextField = "Description";
dropDownList.DataBind();
正如您所看到的那样,只要数组具有Value
和Description
属性,它就无关紧要。
答案 1 :(得分:1)
包装器会这样做,你有两种方法:
public class WSData
{
public string Value;
public string Description;
// First approach: single ctor with dynamic parameter
public WSData(dynamic source)
{
this.Value = source.Value;
this.Description = source.Description;
}
// ----- or --------
// Second approach: one ctor for each class
public WSData(FirstTypeFromWS source)
{
this.Value = source.Value;
this.Description = source.Description;
}
public WSData(SecondTypeFromWS source)
{
this.Value = source.Value;
this.Description = source.Description;
}
}
用法是一样的:
WSData yourData = new WSData(data_retrieved_from_service);
// now, bind the WSData object: you have abstracted yourself from
// the service and as a bonus your code can be attached elsewhere more easily
答案 2 :(得分:0)
您可以定义一个由所有四个类(例如IDescriptionValue)实现的接口,并编写一个接受该类型参数的方法,例如:
public interface IDescriptionValue
{
public string Description {get;set;}
public string Value {get;set;}
}
public class CustomClass1 : IDescriptionValue{
public string Description {get;set;}
public string Value {get;set;}
}
//snip...
public class CustomClass4 : IDescriptionValue{
public string Description {get;set;}
public string Value {get;set;}
}
//accepts parameters of type IDescriptionValue
public void setDropdownData(IDescriptionValue inputData){
// your code here
}