簡體   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