从一个类转换到另一个类
本文关键字:转换 另一个 一个 | 更新日期: 2023-09-27 18:10:21
我正在调用一个web服务,它返回四个自定义类之一的数组。所有的类都有相同的内部内容——一个名为Description的字符串和另一个名为Value的字符串。我正在尝试编写一个可以接受这四个类中的任何一个的方法,并将其内容放入下拉列表的数据源中。
是否有一种方法可以将未知的复合类转换为具有相同内容的指定类?还是把内容去掉?
或者我必须用不同的数据类型写四个相同的函数?edit: add code
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;
}
实际上DropDownList
控件要求您将IEnumerable
作为数据源,然后您可以指定DataTextField
和DataValueField
:
dropDownList.DataSource = some_Array_You_Retrieved_From_Your_Web_Service;
dropDownList.DataValueField = "Value";
dropDownList.DataTextField = "Description";
dropDownList.DataBind();
正如你所看到的,数组的实际类型并不重要,只要它有Value
和Description
属性来绑定它。
包装器有两种方法:
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
您可以定义一个由所有四个类(例如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
}