如何在方法中传递泛型参数?自定义MyORM泛型类Insert方法无法传值
正确调用方法及问题修复
1. Insert方法传参方式
你定义的MyORM<T>泛型类的Insert方法要求传入泛型参数T对应的实体实例,你当前声明的是MyORM<StudentInfo>类型的实例,所以需要先构造StudentInfo对象并给属性赋值,再传给Insert方法,修改后的Main方法如下:
static void Main(string[] args) { // 先实例化要插入的学生实体,填充对应字段值 StudentInfo newStudent = new StudentInfo() { // 按照你StudentInfo类的实际属性替换下面的字段和值 StudentId = 1001, StudentName = "李明", Age = 17, Grade = "高二" }; var orm = new MyORM<StudentInfo>(DbConnection.connectionString); // 将构造好的实体对象作为参数传入Insert方法 orm.Insert(newStudent); }
2. 原MyORM类Insert方法的遗漏问题
按你当前贴出的代码,即使传参正确也无法完成数据插入,还有两处需要修正:
- 参数赋值逻辑错误:当前给SqlCommand添加参数时没有指定参数名,会和SQL语句里的@参数不匹配,需要修改参数添加逻辑:
// 原代码:command.Parameters.Add(property.GetValue(item)); // 修改为: command.Parameters.AddWithValue("@" + property.Name, property.GetValue(item));
- 缺少命令执行逻辑:当前只构造了SqlCommand对象,没有打开连接、执行插入命令,需要在Insert方法末尾补充执行逻辑:
try { if(_sqlConnection.State != System.Data.ConnectionState.Open) { _sqlConnection.Open(); } command.ExecuteNonQuery(); } finally { if(_sqlConnection.State != System.Data.ConnectionState.Closed) { _sqlConnection.Close(); } }
内容的提问来源于stack exchange,提问作者Mithun CH
相关产品推荐
相关产品推荐

