有没有办法将数据从DataReader直接存储到List <class>

时间:2015-04-22 09:43:44

标签: c# reflection

我正在从SqlCommand创建一个datareader,我目前将此信息存储在具有以下内容的类中

    private object PopulateObjectWithFields(SqlDataReader read, Type className)
    {
        var gd = Activator.CreateInstance(className);
        for (int i = 0; i < read.FieldCount; i++)
        {
            var type = gd.GetType();

            var fi = type.GetField(read.GetName(i));
            if (fi != null)
            {
                if (!Convert.IsDBNull(read[i]))
                {
                    try
                    {
                        fi.SetValue(gd, read[i]);
                    }
                    catch
                    {
                        throw new Exception(string.Format("Unable to set {0}. Class type {1}. DB Type {2}", read.GetName(i), fi.FieldType.Name, read[i].GetType().Name));
                    }
                }
            }
            else
            {
                var pi = type.GetProperty(read.GetName(i));
                if (pi != null)
                {
                    if (!Convert.IsDBNull(read[i]))
                    {
                        try
                        {
                            pi.SetValue(gd, read[i]);
                        }
                        catch
                        {
                            throw new Exception(string.Format("Unable to set {0}. Class type {1}. DB Type {2}", read.GetName(i), fi.FieldType.Name, read[i].GetType().Name));
                        }
                    }
                }
            }
        }
        return gd;
    }

这完美无缺。我现在想要的是将其放在List<class>中,但似乎无法动态创建List<class>

有人可以帮我解决语法问题吗?

var MyList = List<MyClass> //This should be dynamically created

using(var reader = cmd.ExecuteReader())
{
      while (reader.Read())
      {
           MyList.Add(PopulateObjectWithFields(read, MyClass));
      }
}

让我澄清 我不知道读者会有什么专栏,而且我也不知道将要传入哪个类。我有一个通用的方法,需要将任何读者填充到任何类中因为列名与类

中字段的属性匹配

1 个答案:

答案 0 :(得分:2)

你应该使用泛型:

public class SomeClass extends RealmObject {
    private String name;
    private Profile profile;

    public Profile getProfile() {
        return profile;
    }

    public String getName() {
        return name;
    }    

    public void setName(String name) {
        this.name= name;
    }
}

public class Profile extends RealmObject {
    private String firstName;
    private String lastName;
    private String birthdate;
    private boolean newsLetter;
    private boolean push;
    private int userId;
    private Date lastUpdate;
    private RealmList<RealmAddress> addresses;
    private RealmList<RealmGender> genders;
}

除了使用private T PopulateObjectWithFields<T>(SqlDataReader read) where T : new() 而不是T之外,您的方法的实现保持不变,并且您可以使用构造函数直接实例化该类型:

MyClass

从那里,您可以轻松地将对象存储在列表中:

var gd = new T();