我正在使用反射来获取 TryParse 方法信息(为第一个猜出原因的人投票;)。
如果我打电话:
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);
我什么也没得到。我的蜘蛛感知告诉我这是因为第二个参数是一个输出参数。
有人知道我在这里做错了什么吗?
试试这个
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];