首页 > 解决方案 > 使用反射和 new() 启动新的通用类对象

问题描述

当我使用泛型类型进行存储库设计时,我试图启动一个新的类对象,但是,由于在泛型类中,我不知道我的具体类对象可能具有什么属性,我在想是否有任何方法在运行时使用反射,以便.Net检查我的类对象具有哪些属性,并动态为其赋值,这是一个例子,我坚持

    public abstract class AdoRepository<TEntity> : IAdoRepository<TEntity> where TEntity : class, new()
    {
        private readonly string _connection;
        public AdoRepository(string connection)
        {
            _connection = connection;
        }

        public async Task<IEnumerable<TEntity>> GetAllWithStoredProcedureAsync(string storedProcedureName, List<SqlParameter> lstParam)
        {
            DataTable dt = await SqlDataHelper.ExecuteDataTableAsync(_connection, storedProcedureName, lstParam);

            return (from row in dt.Select()
                    select new TEntity()
                    {
                        // Question: anyway to use reflection here so that like
                        // Below is what I am trying to do but not be able to
                        foreach (Property p in TEntity.Properties) {
                             switch p.DataType
                                 case 'Int32':
                                      p.Value = Convert.ToInt32(row[p.Name].ToString());
                                      break;
                                 case 'System.String':
                                      p.Value = row[p.Name].ToString();
                                      break;
                                 ....
                                 default:
                                      p.Value = row[p.Name].ToString();
                                      break;
                        }
                    }).ToList();
        }
    }

标签: c#.netnew-operatorgeneric-programminggeneric-collections

解决方案


推荐阅读