c# - 识别对象类型并在运行时将其传递给函数 typeof()
问题描述
我正在尝试创建一个方法,该方法应该将泛型类作为参数并根据其字段返回数据表。
我到目前为止的方法是:
public DataTable TranformClassIntoDataTable<T>(T GenericClass)
{
DataTable dt = new DataTable();
Type objType = typeof(T);
FieldInfo[] info = objType.GetFields();
if (info.Length != 0)
{
for (int i = 0; i < info.Length; i++)
{
// PROBLEM HERE: the part inside of the typeof() isn't accepted by C#
dt.Columns.Add(info[i].Name, typeof(info[i].GetType());
}
}
else
{
throw new ArgumentException("No public fields are defined for the current Type");
}
return dt;
}
当我尝试运行它时得到的错误如下: Array size cannot be specified in a variable declaration
解决方案
您应该更改此声明
dt.Columns.Add(info[i].Name, typeof(info[i].GetType());
到以下
dt.Columns.Add(info[i].Name, info[i].FieldType);
Add
显然,方法接受string
列名和Type
列类型。FieldType
属性包含该字段所属的对象类型
推荐阅读
- xamarin.forms - OpenTok Xamarin 表单
- python - 模块化猜猜游戏循环
- java - 在多项目 gradle 设置中引用子项目的主类
- html - 自动更改数组中元素的类型
- python-3.x - 如何通过 pandas `df.to_sql()` 在已创建的数据库表中插入值
- ios - 如何修复崩溃“UIStatusBarDisplayItemState updatePlacement”?
- wxwidgets - GhostBSD/FreeBSD GNOME 崩溃
- java - 如何访问由构造函数生成的对象变量
- reactjs - React 中的响应式背景图像
- snakemake - 在多个集群环境(LSF、SGE)中具有 mem_mb 资源的 Snakemake 集群命令