首页 新闻 赞助 找找看

泛型方法如何递归

0
悬赏园豆:200 [已解决问题] 解决于 2011-05-31 16:55

我想写个方法,传入类就可以从xml中得到相应的值,xml读取那块我写两个工具类,负责读取。

private T SetFiledsValue<T>(XmlMachine xmlMachine) where T : new()
{
T result
= new T();
Type type
= typeof(T);
FieldInfo[] fields
= type.GetFields();
foreach (FieldInfo field in fields)
{
if (field.GetType() == typeof(string))
{
field.SetValue(result, xmlMachine.Read(field.Name));
}
else if (field.GetType() == typeof(List<string>))
{
field.SetValue(result, xmlMachine.Reads(field.Name));
}
else
{
//这里我希望递归调用SetFiledsValue<T>(XmlMachine xmlMachine) 这个方法,关键这个<T> 的T怎么传呀,忘大神们指教
}
}

return result;
}

问题补充:

所有的园豆都在这里了 ,希望大家帮忙

newzhq的主页 newzhq | 初学一级 | 园豆:2
提问于:2011-05-31 14:18
< >
分享
最佳答案
0

有两种方法可以处理:

1. 穷尽你可的类型;

2. 要不然从网上找一个“非泛型调用泛型方法”的例子,包装一下调用。

或者你干脆将方法 private T SetFiledsValue<T>(XmlMachine xmlMachine)  where T : new()

转换为 private object SetFiledsValue(Type resultType, XmlMachine xmlMachine);

然后实例化对象的时候用 CreateInstance方法。

我觉得想用几行代码做成一个通用的方法估计会很难。

然后提两点建议:

1. SetFiledsValue似乎改成SetFieldsValue更合规;

2. 如果需要多次调用 SetFiledsValue,建议 type.GetFields() 缓存一下。

收获园豆:200
睁开眼睛看世界 | 菜鸟二级 |园豆:412 | 2011-05-31 16:16
。。。
newzhq | 园豆:2 (初学一级) | 2011-05-31 16:22
我在网上也找到了例子,在你回答之前 , 谢谢
MethodInfo fetchMethod = oObject.GetType().GetMethod("Fetch", new Type[] { typeof(MyCriteria) });
MethodInfo genericFetchMethod = fetchMethod.MakeGenericMethod(oTypeFetch);

genericFetchMethod.Invoke(oObject, new object[] { oCriteria });
newzhq | 园豆:2 (初学一级) | 2011-05-31 16:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册