You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在方法中传递泛型参数?自定义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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 15:54:02