Puede escribir algo como esto:
public delegate bool TryParser<T>(string input, out T result);
public static bool TryParse<T>
(string toConvert, out T result, TryParser<T> tryParser = null)
{
if (toConvert == null)
throw new ArgumentNullException("toConvert");
// This whole block is only if you really need
// it to work in a truly dynamic way. You can additionally consider
// memoizing the default try-parser on a per-type basis.
if (tryParser == null)
{
var method = typeof(T).GetMethod
("TryParse", new[] { typeof(string), typeof(T).MakeByRefType() });
if (method == null)
throw new InvalidOperationException("Type does not have a built in try-parser.");
tryParser = (TryParser<T>)Delegate.CreateDelegate
(typeof(TryParser<T>), method);
}
return tryParser(toConvert, out result);
}
Y luego llamar así:
int result;
bool success = TryParse("123", out result);
Realmente no recomendaría esto a menos que tenga algún escenario que lo requiera.
Tal vez podría utilizar algo de System.Reflection. No he tratado los genéricos con Reflection, pero podría ir como get type info, ver si 'TryParse()' existe, si es así, 'Invoke()', de lo contrario devolvería false. – cyanic
Relacionados: http://stackoverflow.com/a/6160588/445517 – CodesInChaos
En particular, consulte http://stackoverflow.com/a/2961921/103167 Solo agregue copiando el resultado nuevamente. –