动态传递通用对象 [英] Pass generic object dynamically

查看:120
本文介绍了动态传递通用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to dynamically show a table depending on what tableName user has selected from dropdown. I am passing a json object from my web Controller(.Net Core) so in order to do it, I am first converting my dataTable to list of objects using function

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;
        }
    }



并在我的获取请求中调用此函数


and call this function in my 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);
}



现在问题是我需要告诉我的班级名称(例如,在这种情况下为CSBM_AGE_BAND),具体取决于用户选择的内容下拉列表(TableNameSelected)。



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



我尝试了什么:



我尝试通过反射来做但没有帮助不大。



我还想知道如果.net核心中存在任何函数,它可以直接将数据集转换为json对象(尝试过JsonConvert.SerializeObject但是无法通过打字稿访问它)。这就是我在客户端检索的方式。




Now the issue is that I need to tell my class Name (eg CSBM_AGE_BAND in this case) depending on what user has selected in dropdown (TableNameSelected).

Is there any way by which I can dynamically pass this class name to my function ConvertTableToList() ?

What I have tried:

I tried doing it by reflection but didn't help much.

I would also like to know that if any function exists in .net core which can directly convert dataset to json object (tried JsonConvert.SerializeObject but wasn't able to access it by typescript). This is how I am retrieving at client side.

getTableColumnDetailsByTableName(TableName: string): void {
        this.coverMeService.getTableColumnDetailsByTableName(TableName)
            .subscribe(data => { this.TableColumnDetails = data; } );
    }

推荐答案

使用非泛型方法转换 DataTable

Use a non-generic method to convert the DataTable:
public static List<object> ConvertTableToList(this DataTable table, Type itemType)
{
    List<object> result = new List<object>();
    
    foreach (var row in table.AsEnumerable())
    {
        object item = Activator.CreateInstance(itemType);
        
        foreach (var prop in itemType.GetProperties())
        {
            prop.SetValue(item, Convert.ChangeType(row[prop.Name], prop.PropertyType), null);
        }
        
        result.Add(item);
    }
    
    return result;
}

用法:

Type itemType = GetItemTypeFromTableName(TableNameSelected);
List<object> TableDetailsInList = ConverterClass.ConvertTableToList(TableDetails, itemType);



现在您只需要弄清楚如何从表名映射到项类型。例如:


Now you just need to work out how to map from the table name to the item type. For example:

private static readonly IReadOnlyDictionary<string, Type> ItemTypeMap = new Dictionary<string, Type>
{
    ["CSBM_AGE_BAND"] = typeof(CSBM_AGE_BAND),
    ...
};

private static Type GetItemTypeFromTableName(string tableName) => ItemTypeMap[tableName];


这篇关于动态传递通用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆