【问题标题】:Pass Generic Object Dynamically动态传递通用对象
【发布时间】:2018-04-20 21:59:10
【问题描述】:

我正在尝试根据用户从下拉列表中选择的 tableName 来动态显示表格。我从我的网络控制器(.Net Core)传递一个 json 对象,所以为了做到这一点,我首先使用函数将我的 dataTable 转换为对象列表

public static List<T> ConvertTableToList<T>(this DataTable table) where T : class, new()
        {
            try
            {
                List<T> list = new List<T>();
            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();

                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch(Exception ex)
                    {
                        throw ex;
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        catch
        {
            return null;
        }
    }

并在我的 Get Request 中调用此函数

    public IActionResult GetTableDetailsByTableName(string TableNameSelected)
    {
        //To get the data for the Table Selected
        DataTable TableDetails = ReferenceTableLogics.getTableDetails(TableNameSelected);

        var TableDetailsInList = ConverterClass.ConvertTableToList<CSBM_AGE_BAND>(TableDetails);
        return Ok(TableDetailsInList);
    }

现在的问题是我需要根据用户在下拉列表中选择的内容 (TableNameSelected) 告诉我的班级名称(例如 CSBM_AGE_BAND)。

有什么方法可以动态地将这个类名传递给我的函数ConvertTableToList

【问题讨论】:

  • 使用反射,请看下面我的回答
  • 如果我的回答对你有用,你能投票和/或评论吗?

标签: asp.net-core http-get generic-list


【解决方案1】:

使用反射你可以调用你的通用扩展方法:

Type genericType = Type.GetType("YourNamespace.ConverterClass");
MethodInfo methodInfo = typeof(ConverterClass).GetMethod("ConvertTableToList", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(genericType);
var TableDetailsInList = methodInfo.Invoke(null, new object[]{ TableDetails });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 2018-11-24
    相关资源
    最近更新 更多