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

C#如何从dynamic动态类型中获取传入的Student/Course实际模型类型信息

解决方案

在使用dynamic的前提下完全可以获取到传入模型的真实类型信息,以下是具体实现方案:

1. 获取动态对象的真实类型

dynamic只是C#提供的运行时动态解析语法糖,传入的对象本身的CLR类型信息不会丢失,直接调用GetType()方法即可获取:

public bool AddAll(dynamic model)
{
    // 先判空避免空引用异常
    if (model == null)
        throw new ArgumentNullException(nameof(model));
    
    // 拿到的就是Student/Course的实际类型
    Type realType = model.GetType();
    // 后续逻辑
}

2. 获取对应表名

有两种常用实现方式:

方式一:通过特性标注获取(推荐)

给模型类加上TableAttribute(如果用EF的话本身就自带该特性,无需自定义):

[Table("Student")]
public class Student
{
    // 字段定义
}

[Table("Course")]
public class Course
{
    // 字段定义
}

然后在AddAll方法里反射读取特性值即可:

var tableAttr = realType.GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault() as TableAttribute;
string tableName = tableAttr?.Name ?? realType.Name;

方式二:直接类型判断

如果不想加特性,也可以直接通过类型匹配获取表名:

string tableName;
if (realType == typeof(Student))
    tableName = "Student";
else if (realType == typeof(Course))
    tableName = "Course";
else
    throw new NotSupportedException("不支持的模型类型");

3. 获取对应表总数据量

拿到表名或者类型之后就可以很方便的统计数据量,以EF Core为例:

// 假设已经注入了对应的DbContext
int totalCount = dbContext.Set(realType).Count();

如果是用自定义服务类的话,也可以根据类型判断调用对应服务的统计方法即可。

额外优化建议

如果可以调整方法定义的话,更推荐用泛型替代dynamic,既保留了对不同模型的适配能力,还能获得编译时类型检查,避免运行时错误:

public bool AddAll<T>(T model)
{
    Type realType = typeof(T);
    // 后续逻辑和上述完全一致
}

内容的提问来源于stack exchange,提问作者XenDex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:57:01