我想使用反射,安裝簡單對象方法PropertyInfo.SetValue(obj, value, index)
時不同的泛型列表附加到一個類的實例對象返回異常{"Parameter count mismatch."}
當值的List<SomeType>
實例(而不是一個字符串,int,布爾甚至是一個自定義類)。加入泛型列表的情況下使用反射
這個總結可能沒有多大意義;以下可能有助於解釋我正在嘗試做什麼。
說,我們正在努力填充反射以下類:
public class Foo
{
public virtual int someInt {get; set;}
public virtual IList<SomeClass> list {get; set;}
}
的方法可能看起來是這樣的:嘗試添加列表的實例時
public static T Parse<T>(HttpRequest request) where T : new()
{
returnObj = new T();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo p in properties)
{
// Get a meaningful property name
string ins = System.Text.RegularExpressions.Regex.Replace(p.PropertyType.FullName, "([^,]*),.*$", "$1");
switch(ins)
{
// populate int
case "System.Int32":
p.SetValue(returnObj, Int32.Parse(request[p.Name]) , null);
break;
// populate list
case "System.Collections.Generic.IList`1[[SomeNamespace.Domain.SomeClass":
IList<SomeClass> list = new List<SomeClass>();
foreach (string s in request[p.Name].Split(','))
{
list.Add(new SomeClass(s));
}
// This will throw the exception 'Parameter count mismatch.'
p.SetValue(returnObj, list, null);
break;
}
}
return returnObj;
}
但是(IList的)這樣就拋出了一個異常。
編輯:澄清,如果已經超過此方法用細齒梳(斷點)(以及,在一個應用程序中的,不完全是這一個)和所有變量如預期填充;直到SetValue
拋出一個異常;如果有人需要更多的信息,請問。
EDIT2:所以我建立了一個更小的應用程序來進行測試(爲了上傳它作爲一個例子);而且我無法重現我自己的問題;正如你們許多人所建議的那樣。當我設法追蹤這個問題時,我會更新這個問題。它可能是一些微不足道的東西,因爲這些東西經常是(原始代碼庫很大,因此不適合我發佈)。感謝您迄今爲止的所有幫助,並且對浪費您的時間表示歉意。
你確定p是列表?你的實際類是否暴露了一個與列表類型相同的索引器? – Frobzig
我確定,我突出了它的屬性名稱以及類型。 – Waltzy
你能展示一個簡短但完整的程序來證明問題嗎? –