首页 > 解决方案 > 识别对象类型并在运行时将其传递给函数 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

标签: c#.netgenericsdatatable

解决方案


您应该更改此声明

dt.Columns.Add(info[i].Name, typeof(info[i].GetType()); 

到以下

dt.Columns.Add(info[i].Name, info[i].FieldType); 

Add显然,方法接受string列名和Type列类型。FieldType属性包含该字段所属的对象类型


推荐阅读