为Type.GetMethod指定params

我正在使用reflection来获取TryParse方法信息(为第一个人提供upvote以猜测原因;)。

如果我打电话:

typeof(Int32).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string) }, null); 

我得到一个方法,但稍微扩展一下:

 typeof(Int32).GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string), typeof(Int32) }, null); 

我一无所获。 我的spidersense告诉我这是因为第二个参数是out参数。

谁知道我在这里做错了什么?

试试这个

 typeof(Int32).GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string), typeof(Int32).MakeByRefType() }, null); 

就像@ Jab一样,但是更短一点:

 var tryParseMethod = typeof(int).GetMethod(nameof(int.TryParse), new[] { typeof(string), typeof(int).MakeByRefType() }); // use it var parameters = new object[] { "1", null }; var success = (bool)tryParseMethod.Invoke(null, parameters); var result = (int)parameters[1];