我正在尝试使用反射将通用列表附加到类的实例,这与附加简单对象方法不同,当值是(而不是字符串、int、bool 甚至自定义类的实例)时PropertyInfo.SetValue(obj, value, index)
返回异常)。{"Parameter count mismatch."}
List<SomeType>
那个夏天可能没有多大意义;以下内容可能有助于解释我正在尝试做的事情。
假设我们正在尝试用反射填充以下类:
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;
}
但是,当尝试以这种方式添加 List (IList) 的实例时,会引发异常。
编辑:澄清一下,如果用细齿梳(断点)(嗯,应用程序中的那个,不完全是这个)完成了这种方法,并且所有变量都按预期填充;直到SetValue
抛出异常;如果有人需要更多信息,请询问。
Edit2:所以我构建了一个较小的应用程序来测试它(以上传它作为示例);而且我无法重新创建自己的问题;正如你们中的许多人所建议的那样。当我设法找到它时,我会用这个问题更新这个问题。它可能是微不足道的,因为这些事情经常发生(原始代码库很大,因此不适合我发布)。感谢您迄今为止的所有帮助,并为浪费您的时间而道歉。