简体   繁体   中英

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. Rather than copy and paste the code again in my library I want to also make the below work for 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.

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. It should automatically be available to a variable of type IList<T> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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