简体   繁体   English

在C#中动态设置列表对象类型

[英]Dynamically set list object type in c#

I have a List object that I need to be able to swap the object type dynamically. 我有一个List对象,我需要它能够动态交换对象类型。 Basically I have: 基本上我有:

List<DataBaseItems> items = new List<DataBaseItems>();

I will then perform some filtering on that list with LINQ then bind to a telerik grid. 然后,我将使用LINQ在该列表上执行一些过滤,然后绑定到telerik网格。 I need to swap out the object based on an id that i get. 我需要根据获得的ID换出对象。 My goal is to build a custom control that can use it's filter button for multiple reports where the report data is coming from the above list. 我的目标是建立一个自定义控件,该控件可以将其过滤器按钮用于多个报表,其中报表数据来自上述列表。 Report A may use the above list and report B needs a completely different object but has the same actions on it. 报告A可能使用上面的列表,报告B需要一个完全不同的对象,但对其具有相同的操作。

创建一个接口并将其实现到您实现的任何对象中。

public interface ICustomListFilter<T> 
       where T:class
{
    public void FilterAndBindMyList(List<T> myList);
}

public class ReportOneFilter:ICustomListFilter<MyFirstType>
{
    public void FilterAndBindMyList(List<MyFirstType> items)
    {

        // your filtering and binding code goes here, such as items.Where(i => ...
    }
}

public class ReportTwoFilter:ICustomListFilter<MySecondType>
{
    public void FilterAndBindMyList(List<MySecondType> items)
    {

        // your another filtering and binding algorithm goes here, such as items.Select(i => ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM