为Type.GetMethod指定params

Kha*_*zor 19 c# reflection

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

如果我打电话:

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

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

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

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

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

Jab*_*Jab 41

试试这个

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


Joh*_*son 6

像@Jab's 但有点短:

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];
Run Code Online (Sandbox Code Playgroud)