开发者

Specifying out params for Type.GetMethod

开发者 https://www.devze.com 2023-02-01 09:38 出处:网络
I\'m using reflection to get at the TryParse method info (upvote for the first person to guess why ;).

I'm using reflection to get at the TryParse method info (upvote for the first person to guess why ;).

If I call:

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

I get a method back, but extending this slightly:

typeof(Int32).GetMethod("TryParse",
  BindingFlags.Static | BindingFlags.Public,
  null,
  new Type[] { typeof(strin开发者_JS百科g), typeof(Int32) },
  null);

I get nothing back. My spidersense is telling me it's because the second parameter is an out parameter.

Anyone know what I've done wrong here?


Try this

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


Like @Jab's but a little shorter:

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];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号