我有这种扩展方法。

    public static List<Framework.Model> FetchAll(this Framework.Model model)
    {
        List<Framework.Model> models = new List<Framework.Model>();

        StringBuilder Fields = new StringBuilder();

        var properties = GetProperties(model);

        foreach (var p in properties)
        {
            if (!p.Name.Equals("Table"))

                Fields.Append(p.Name + ",");
        }

        Fields.Length--;


        System.Data.DataTable data = (System.Data.DataTable)engine.RunDataTable("select " + Fields.ToString() + " from " + model.Table + ";").Data;


        foreach (System.Data.DataRow rw in data.Rows)
        {
            foreach (System.Data.DataColumn col in data.Columns)
            {
                foreach (var p in properties)
                {
                    if (col.ColumnName.Equals(p.Name))
                    {
                        if (p.PropertyType == typeof(DateTime?))
                        {
                            p.SetValue(model, DateTime.Parse(rw[col.ColumnName].ToString()));
                        }
                        else
                        {
                            p.SetValue(model, Convert.ChangeType(rw[col.ColumnName], p.PropertyType));

                        }
                    }

                }

            }


            models.Add(model);

        }

        return models;


    }


我有这个基础课。

public interface Model
{
    string Table { get; set; }
}


我也有这个子类

 public class Department : Framework.Model
{
    public Department()
    {
        this.Table = "departments";
    }

    public int Dbid { get; set; }
    public string Code { get; set; }
    public DateTime? created_at { get; set; }
    public DateTime? updated_at { get; set; }

    public string Table
    {
        get; set;
    }
}


我现在尝试使用上面的扩展方法。

List<Model.Department> depts = new List<Model.Department>();
depts = new Model.Department().FetchAll();


但是它是编译器错误,因为它无法将基类转换为子类。
我的问题仅是如何返回子类,因为我只想在调用扩展方法时返回该特定表(它是我的子类)上数据库中的所有数据,因此我想获取子类列表。

顺便说一句,扩展方法是我希望它可以灵活接受其他子类,这就是我以这种方式构建它的原因。

最佳答案

这简单。您只需要使其通用即可。

public static List<T> FetchAll<T>(this T model) where T: Framework.Model
{
    List<T> models = new List<T>();
    ...
    foreach (System.Data.DataRow rw in data.Rows)
    {
        <... modifying model's properties ...>
        models.Add(model);
    }
    ...
    return models;
}


之后,您甚至不需要指定通用类型-编译器将从您的代码中推断出它:

var depts = new Model.Department().FetchAll();
// depts is List<Model.Department> if you've built class hierarchy correctly


但是,您的代码还有另一个问题。让我们看一下上面的循环。您试图一遍又一遍地将同一对象添加到列表中。由于您正在修改对象的属性,因此将获得对同一对象的N个引用的列表,这些引用具有从数据库中获取的表的最后一行的属性。我不认为这是您真正需要的,但是我实际上并没有得到您需要的,因此除非您明确说明,否则无法提供任何建议。

09-10 03:58
查看更多