简体   繁体   English

多个泛型的扩展方法

[英]Extension method on multiple generics

I've found the below "Convert to Datatable" code which I've altered to be an extension method for the IList interface. 我发现以下“转换为数据表”代码已被更改为IList接口的扩展方法。 Rather than copy and paste the code again in my library I want to also make the below work for ICollection. 除了希望将代码再次复制并粘贴到我的库中之外,我还想使以下内容适用于ICollection。 I can copy and paste the code and change the IList at the top, then then I would have two copies of the same script. 我可以复制并粘贴代码,并在顶部更改IList,然后我将拥有同一脚本的两个副本。

public static DataTable ConvertToDatatable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    DataTable dataTable = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        dataTable.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        dataTable.Rows.Add(values);
    }
    return dataTable;
}

I've even tried changing the first line to something like 我什至尝试将第一行更改为

public static DataTable ConvertToDatatable<T>(this N<T> data) where N : IList<T>, ICollection<T>

but having no luck. 但没有运气。 Is it possible to make the extension to work on the multiple collection types? 是否可以使扩展适用于多种集合类型?

Since an IList<T> is an ICollection<T> it should be sufficient to just define the extension method on the ICollection<T> type. 由于IList<T>ICollection<T>因此只需在ICollection<T>类型上定义扩展方法就足够了。 It should automatically be available to a variable of type IList<T> . 它应该自动可用于类型为IList<T>的变量。

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

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