Reflexión sobre un método estático sobrecargado utilizando un parámetro out
Tengo algunos problemas al invocar un método estático sobrecargado con un parámetro de salida a través de la reflexión y agradecería algunos punteros.
Estoy buscando crear dinámicamente un tipo comoSystem.Int32
oSystem.Decimal
y luego invoque la estáticaTryParse(string, out x)
método sobre el mismo.
El siguiente código tiene dos problemas:
t.GetMethod("TryParse", new Type[] { typeof(string), t } )
no puede devolver el MethodInfo que espero
mi.Invoke(null, new object[] { value.ToString(), concreteInstance })
parece tener éxito pero no establece el parámetroconcreteInstance
al valor analizado
Entretejido en esta función, puede ver un código temporal que demuestra lo que debería suceder si eltype
el parámetro se estableció enSystem.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;
}
¿Qué debo hacer para asegurarme de que mit.GetMethod()
la llamada devuelve el MethodInfo correcto? ¿Qué necesito hacer para tenerconcreteInstance
correctamente configurado en mimi.Invoke()
¿llamada?
Sé que hay muchas preguntas sobre este tema, pero la mayoría de ellas involucran métodos genéricos estáticos o métodos estáticos que no están sobrecargados.Esta pregunta es similar pero no es un duplicado.