如果您打算在转发器中使用它(我希望您实际上是指 ListView),那么只需在接口中定义您的属性,然后在 Deal 和 Store 类中实现接口。然后您可以将列表绑定到转发器/列表视图并按名称调用属性。不需要任何诡计。通过这样做,接口保证您的属性可用(否则 DataTextvalue 将在绑定期间中断)。
换句话说,如果您要绑定到 ListView,则显示属性需要在 Store 和 Deal 类中命名相同。因此,您不妨以最基本的形式使用该接口:
protected Page_Load(object sender, EventArgs e)
{
var list = new List<IWatchamacallit>();
list.Add(new Store { Property1 = "Store1", Property2 = "StoreInfo"});
list.Add(new Store { Property1 = "Store2", Property2 = "StoreInfo" });
list.Add(new Deal { Property1 = "Deal1", Property2 = "DealInfo" });
list.Add(new Deal { Property1 = "Deal2", Property2 = "DealInfo" });
myListView.DataSource = list;
myListView.DataBind();
/* from here just set your page controls to call the properties
for instance:
<asp:Label Text='<%# Eval("Property1") %>' />
<asp:Label text='<%# Eval("Property2") %>' />
*/
}
public interface IWatchamacallit
{
string Property1 { get; set; }
string Property2 { get; set; }
}
public class Store : IWatchamacallit
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class Deal : IWatchamacallit
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
您的输入将绑定看起来像:
Property1 Property1
=====================
Deal1 DealInfo
Deal2 DealInfo
Store1 StoreInfo
Store2 StoreInfo
您需要保留的任何其他值(如 dealId 或 storeId)都可以作为属性添加到您的类中。只需确保在界面中定义它们并使用一致的命名即可。通过这样做,您可以在保持类结构的同时用两种不同的类型填充列表。如果您稍后需要从列表中选择它们,您可以像这样抛出:
foreach (var item in list)
{
var tempContainer = Activator.CreateInstance(item.GetType());
tempContainer = item;
}
或其他几种方式中的任何一种,具体取决于您要完成的工作。