繁体   English   中英

.Net反射使用泛型参数调用函数-如何将类型传递给函数

[英].Net Reflection calling a function with a generic parameter - How to pass the type to the function

嗨,这是我的第一个问题! 我真的在下面的代码中苦苦挣扎:

我有这些课:

public class Home {
    public List<Parameter> Parameter { get; set; }
}

我也有一个与此规格的功能:

public static List<T> DataTableMapToList<T>(DataTable dtb)
    { ... }

在另一个需要调用这些函数的类中,我需要传递我的类的类型,但是我处于反射属性循环中:

public void Initialize(ref object retObject)
    {
        using (var db = this)
        {

            db.Database.Initialize(force: false);

            var cmd = db.Database.Connection.CreateCommand();
            cmd.CommandText = sStoredProcedure;

            try
            {
                // Run the sproc
                db.Database.Connection.Open();
                DbDataReader reader = cmd.ExecuteReader();

                DataSet ds = new DataSet();
                ds.EnforceConstraints = false;
                ds.Load(reader, LoadOption.OverwriteChanges, sTables);

                var propertys = GetGenericListProperties(retObject);

                foreach (DataTable table in ds.Tables) {

                    foreach (var info in propertys)
                    {

                        if (info.Name == table.TableName)
                        {

                            Type myObjectType = info.PropertyType;

                            // Create an instance of the list
                            var list = Activator.CreateInstance(myObjectType);

                            var list2 = DataTableMapToList<???>(table).ToList();
                            //Where the variable myObjectType is the TYPE of the class where I need to pass on the ??? marker

                            info.SetValue(retObject, list, null);

                        }

                    }

                }

            }
            finally
            {
                db.Database.Connection.Close();
            }

        }

    } 

其中:retObject-> Home的实例; 信息->这是Home.Parametro属性;

我想通过反射来动态设置属性。 无需调用泛型类型的函数,一切都可以正常工作。 但是我需要调用该函数以正确填充属性。

我已经尝试了一切:

作为对象传递并尝试转换(我得到IConverter错误必须实现);

试图将我所有的代码-仅用于测试-DataTableMapToList(),甚至因此出现对象转换错误;

强制发送最后一个变量的列表,但再次出现转换器错误。

我不知道我是否真正真正需要什么,但是我花了大约4个小时来寻找解决方案,直到知道为止。

假设有一个带有静态泛型函数的类:

public static class Utils
 {

    public static List<T> DataTableMapToList<T>(DataTable dtb)
    { ... }
 }

可以使用反射来调用它:

 IEnumerable InvokeDataTableMap(DataTable dtb, Type elementType)
 {
       var definition = typeof(Utils).GetMethod("DataTableMapToList");
       var method = definition.MakeGenericMethod(elementType);
       (IEnumerable) return method.Invoke(null, new object[]{dtb});
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM