Skip to main content
 首页 » 编程设计

c#之非通用声明不允许约束

2024年02月06日11java哥

经过一番谷歌后,我发现以下代码可以帮助将数据行转换为特定类

public static void SetItemFromRow(T item, DataRow row) where T : new() 
{ 
    // go through each column 
    foreach (DataColumn c in row.Table.Columns) 
    { 
        // find the property for the column 
        PropertyInfo p = item.GetType().GetProperty(c.ColumnName); 
 
        // if exists, set the value 
        if (p != null && row[c] != DBNull.Value) 
        { 
            p.SetValue(item, row[c], null); 
        } 
    } 
} 
 
// function that creates an object from the given data row 
public static T CreateItemFromRow(DataRow row) where T : new() 
{ 
    // create a new object 
    T item = new T(); 
 
    // set the item 
    SetItemFromRow(item, row); 
 
    // return  
    return item; 
} 
 
public static List CreateListFromTable(DataTable tbl) where T : new() 
{ 
    // define return list 
    List lst = new List(); 
 
    // go through each row 
    foreach (DataRow r in tbl.Rows) 
    { 
        // add to the list 
        lst.Add(CreateItemFromRow(r)); 
    } 
 
    // return the list 
    return lst; 
} 

但他们都给我这个错误“非通用声明不允许约束”我有很多谷歌但对我的功能没有帮助

我想要的主要是制作将数据表转换为类列表的通用函数 &数据行到类

请您参考如下方法:

您忘记了 <T>

        public static void SetItemFromRow<T>(T item, DataRow row) 
        where T : new() 
    { 
        // go through each column 
        foreach (DataColumn c in row.Table.Columns) 
        { 
            // find the property for the column 
            PropertyInfo p = item.GetType().GetProperty(c.ColumnName); 
 
            // if exists, set the value 
            if (p != null && row[c] != DBNull.Value) 
            { 
                p.SetValue(item, row[c], null); 
            } 
        } 
    }