最近在写一个泛型方法,想通过此方法调用实现某些类型的TryParse方法,通过比如int,Date的TryParse方法.如下

1
1
MethodInfo m = typeof(T).GetMethod("TryParse")
但是在反射这些类型的TryPase方法时总是提示"发现不明确的匹配",查看帮助文档发现反射重载的方法必须指定参数类型,于是就增加了参数类型的数组,如下

2
1
Type[] types = new Type[2];
2
types.SetValue(typeof(string), 0);
3
types.SetValue(typeof(T), 1);
4
MethodInfo m = typeof(T).GetMethod("TryParse", types);
方法是匹配了,而且不会出现"发现不明确的匹配"的异常,但是返回的方法m是null,也就是没有反射到这个方法.后来发现问题在于参数类型,因为TryParse的第二个参数类型是out Date,引用类型.用遍历查看Date的TryPase方法的所有参数类型,发现TryPase第二个参数类型是System.Date&,而不是System.Date.刚好Type有个
Type.GetType(string s),通过字符串获取类型的方法,改造之后即可,如下

3
1
private static T Parse<T>(string s)
2
{
3
Type[] types = new Type[2];
4
types.SetValue(typeof(string), 0);
5
types.SetValue(Type.GetType(typeof(T).FullName + "&"), 1);
6
MethodInfo m = typeof(T).GetMethod("TryParse", types);
7
T outPut = default(T);
8
object temp = m.Invoke(null, new object[]
{s, outPut});
9
bool canParse = (bool)temp;
10
11
if (canParse)
12
{
13
types = new Type[1];
14
types.SetValue(typeof(string), 0);
15
return (T)typeof(T).GetMethod("Parse", types).Invoke(null, new object[]
{ s });
16
}
17
else
18
{
19
return default(T);
20
}
21
}