c# - 具有通用类型 T 的 SetValue

标签 c# reflection instance generic-type-argument

我有这个功能: 变量 c获得我类(class)的所有属性<T> 在这种情况下:

c -
Id
Key
Value

public List<T> ReadStoreProceadure<T>(string storeName)
{
    var result = new List<T>();
    var instance = (T) Activator.CreateInstance(typeof (T), new object[] {});
    var c = typeof (T);
    var data = DataReader.ReadStoredProceadures(_factibilidad, storeName); // This part is returning verified data and it's ok

    while (data.Read())
    {
        if (data.HasRows)
        {
            foreach (var item in c.GetProperties())
            {
                //item.SetValue(c, item.Name, null);
            }
        }
    }     
}

我如何将这些值添加到我的实例中 instance并将其添加到我的 result多变的? 可能吗?

最佳答案

我已经为 IDataReader 创建了一个扩展方法,它基本上完成了我认为您正在尝试做的事情:

public static List<T> ToList<T>(this IDataReader dr) where T: new()
{
    var col = new List<T>();
    var type = typeof(T);
    var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

    while (dr.Read())
    {
        var obj = new T();
        for (int i = 0; i < dr.FieldCount; i++)
        {
            string fieldName = dr.GetName(i);
            var prop = props.FirstOrDefault(x => x.Name.ToLower() == fieldName.ToLower());
            if (prop != null)
            {
                if (dr[i] != DBNull.Value)
                {
                    prop.SetValue(obj, dr[i], null);
                }
            }
        }
        col.Add(obj);
    }

    dr.Close();
    return col;
}

但是,您会注意到我选择了相反的工作方式。我没有迭代类型的属性并从 DataReader 获取它们,而是迭代 DataReader 列并检查类型的匹配属性。您应该能够快速修改它以适合您的数据检索方案。

关于c# - 具有通用类型 T 的 SetValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28155333/

相关文章:

python - 错误: unbound method Dragon( ) must be called with Enemy instance as first argument (got Player instance instead)

ios - 如何从不同的 swift 类重置变量/步进值

c# - 为什么 C# 中条件运算符总是返回 int?

c# - 为什么我的 C# 构造函数无法使用我尝试使用的方法?

c# - 如何在c#中的特定位置写入数据?

c# - 如何确定属性是从基类继承还是在派生类中声明?

c# - 创建 COM 互操作类的实例

c# - Linq 检查 null 并按 orderby 替换 null 值

java - 模拟注解方法时的 NPE

java - Private 可见性修饰符的含义