आप कुछ इस तरह लिख सकते हैं:
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);
}
और फिर इसे पसंद फोन:
int result;
bool success = TryParse("123", out result);
मैं वास्तव में इस की सिफारिश नहीं होगा जब तक आप कुछ परिदृश्य है कि यह आवश्यकता है।
शायद तुम System.Reflection से कुछ इस्तेमाल कर सकते हैं। मैंने प्रतिबिंब के साथ जेनेरिकों के साथ निपटाया नहीं है, लेकिन यह टाइप प्रकार की जानकारी जैसा हो सकता है, देखें कि 'TryParse()' मौजूद है, यदि ऐसा है, तो 'Invoke() ', अन्यथा झूठी वापसी करें। – cyanic
संबंधित: http://stackoverflow.com/a/6160588/445517 – CodesInChaos
विशेष रूप से http://stackoverflow.com/a/2961921/103167 पर देखें, परिणाम को वापस कॉपी करना जोड़ें। –