与接口的矛盾差异

时间:2013-02-19 11:04:45

标签: c#-4.0 generics

我有一个接口iExportColumn和一个实现interfce的类ExportColumn。对于实现IExportColumn接口的所有类,ExportColumnCollection类应该是通用的。

public interface IExportColumn
{
    string Header { get; set; }
    string ColumnName { get; set; }
}

public class ExportColumn : IExportColumn
{
    public ExportColumn(){}
    public string Header { get; set; }
    public string ColumnName { get; set; }
}

public class ExportColumnCollection<T> where T: IExportColumn
{
    private List<T> cols;

    public ExportColumnCollection (List<T> c)
    {
        cols = c;
    }

    public T Columninfo (string colname)
    {
    }
      .....
 }

我遇到运行时错误,说无法加载类型ExportColumnCollection

我正在寻找能够实现某些目标的东西 List<IExportColumn> = new List<ExportColumn>();

我有两个实现接口IExportColumn的类,我需要持有一个GenericCollection来处理List

1 个答案:

答案 0 :(得分:0)

您班级的正确用法是:

List<IExportColumn> list= new List<IExportColumn>();
// you may add to the collection any class which implements IExportColumn
list.Add(new ExportColumn1() { ColumnName = "Id" });
list.Add(new ExportColumn2() { ColumnName = "Value" });

ExportColumnCollection<IExportColumn> collection = new 
    ExportColumnCollection<IExportColumn>(list);
var colInfo = collection.ColumnInfo("Id");