7

何かを Action または Func に自動的にキャストする方法を見つけようとしていますが、思いつくのは次のようなものです。

[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 {}
    }
}

これを行うには、より良い/より簡単な方法が必要です。何か考えはありますか?

4

3 に答える 3

3

Coincoin が言うように、C# ではメソッドのオーバーロードが熱狂的に愛されているため、うまく機能しません。人々が使用している唯一の回避策は、Action メソッドと Func メソッドを作成することです。

public Action Action(Action f) { return f; }
public Action<A> Action<A>(Action<A> f) { return f; }
...
public Func<A,B,C,D,E> Func(Func<A,B,C,D,E> f) { return f; }

それらをすべて「F」と呼んで、ある種の短い構文を取得することもできます。

F(BadMethod).NoExceptions();

これらのメソッドをクラスで定義せず、Funcs ユーティリティなどに配置することを決定する場合があります。F で別名を付けても、それほど悪くはありません。

F.F(BadMethod).NoException();

しかし、全体的にはまだひどいです:(。

于 2009-02-13T04:06:22.840 に答える
1

F#では、はるかに優れた型推論システムを提供することで、この種のことを非常に自然に行うことができます。

于 2010-01-08T18:19:05.603 に答える