c# - 使用反射和 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();
}
}
解决方案
推荐阅读
- laravel - 如何在 Laravel 中使用一个用户模型创建单独的登录视图和重定向
- c - 使用字符串和固定大小的动态内存分配
- symfony - 不使用自定义子资源路径时关系实体字段上的安全投票者
- c++ - 如何在 MFC 中从弹出所有者绘制 ListBox 中获取 selchange msg
- markdown - Doxygen 中的 Markdown 文件,两个谜题
- ios - MapKit Tile Overlay 需要很长时间才能加载
- javascript - 如果数组中已存在特定项,则删除并将对象项添加到数组中并更改对象键
- memory - 在 128 个内核上进行大型模拟的内存出现硬件错误
- database - 如何定义没有主键的持久表?
- python - 找到一个没有被另一个词继续的词