मैं एक तरह से स्वचालित रूप से एक कार्य या समारोह और सबसे अच्छा मैं के साथ आ सकते हैं के लिए कुछ कास्ट करने के लिए यह पता लगाने की कोशिश कर रहा हूँ कुछ इस तरह है:मैं स्पष्ट रूप से एक्सटेंशन विधियों के साथ प्रतिनिधि क्यों नहीं डाल सकता?
[TestFixture]
public class ExecutionTest
{
public void BadMethod()
{
throw new Exception("Something bad happened");
}
[Test]
public void TestBadMethod()
{
// Want this, but it won't work!!
// BadMethod.Execute().IgnoreExceptions();
// Ick
((Action)BadMethod).Exec().IgnoreExceptions();
// Still ick
((Action)BadMethod).IgnoreExceptions();
// Do not want
ExtensionMethods.Exec(BadMethod).IgnoreExceptions();
// Better but still meh
this.Exec(BadMethod).IgnoreExceptions();
}
}
public static class ExtensionMethods
{
public static Action Exec(this Action action)
{ return action; }
public static Action Exec(this object obj, Action action)
{ return action; }
public static void IgnoreExceptions(this Action action)
{
try { action(); }
catch {}
}
}
एक बेहतर/आसान करने के लिए जिस तरह से करने के लिए है यह, कोई विचार?
यह सुनिश्चित नहीं है कि यह विधि ओवरलोड का मुद्दा है क्योंकि संकलक यह पता लगाएगा कि कौन से कॉल करना है। लेकिन यह अब तक का सबसे अच्छा जवाब है जिसे मैंने देखा है ... –