Reflexão sobre um método estático sobrecarregado usando um parâmetro out
Estou tendo alguns problemas ao chamar um método estático sobrecarregado com um parâmetro out via reflexão e gostaria de receber alguns ponteiros.
Eu estou olhando para criar dinamicamente um tipo comoSystem.Int32
ouSystem.Decimal
e, em seguida, chame o staticTryParse(string, out x)
método nele.
O código abaixo tem dois problemas:
t.GetMethod("TryParse", new Type[] { typeof(string), t } )
falha ao retornar o MethodInfo que eu espero
mi.Invoke(null, new object[] { value.ToString(), concreteInstance })
parece ter sucesso, mas não define os parâmetrosconcreteInstance
para o valor analisado
Entrelaçado nesta função, você pode ver algum código temporário demonstrando o que deve acontecer se otype
parâmetro foi definido comoSystem.Decimal
.
public static object Cast(object value, string type)
{
Type t = Type.GetType(type);
if (t != null)
{
object concreteInstance = Activator.CreateInstance(t);
decimal tempInstance = 0;
List<MethodInfo> l = new List<MethodInfo>(t.GetMethods(BindingFlags.Static | BindingFlags.Public));
MethodInfo mi;
mi = t.GetMethod("TryParse", new Type[] { typeof(string), t } ); //this FAILS to get the method, returns null
mi = l.FirstOrDefault(x => x.Name == "TryParse" && x.GetParameters().Length == 2); //ugly hack required because the previous line failed
if (mi != null)
{
try
{
bool retVal = decimal.TryParse(value.ToString(), out tempInstance);
Console.WriteLine(retVal.ToString()); //retVal is true, tempInstance is correctly set
object z = mi.Invoke(null, new object[] { value.ToString(), concreteInstance });
Console.WriteLine(z.ToString()); //z is true, but concreteInstance is NOT set
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
return concreteInstance;
}
return value;
}
O que preciso fazer para garantir que meust.GetMethod()
chamada retorna o MethodInfo correto? O que eu preciso fazer para terconcreteInstance
definido corretamente no meumi.Invoke()
ligar?
Eu sei que existem várias perguntas sobre esse tópico, mas a maioria delas envolve métodos genéricos estáticos ou métodos estáticos que não são sobrecarregados.Essa questão é semelhante, mas não duplicado.