メソッド呼び出しで属性が適用されているかどうかをテストする拡張メソッドを作成し、そのメソッドをラムダ式として指定したいと考えています。現在、私は次の(機能する)アプローチを持っていますが、このコードの見た目が本当に好きではありません:
// Signature of my extension method:
public static bool HasAttribute<TAttribute, TDelegate>(this Expression<TDelegate> method)
// Usage (current code)
Expression<Func<AccountController, LogInModel, string, ActionResult>> mut = (c, m, s) => c.LogIn(m, s);
mut.HasAttribute<ExportModelStateAttribute, Func<AccountController, LogInModel, string, ActionResult>>().ShouldBeTrue();
ご覧のとおり、デリゲートの型を 2 回指定する必要がありますが、どちらも見栄えがよくありません...
// Usage (if I had my way...)
var mut = (c, m, s) => c.LogIn(m, s);
mut.HasAttribute<ExportModelStateAttribute>().ShouldBeTrue();
しかし、それは少し要求が多すぎるかもしれないことに気づきました。
現在のコードから型引数をリファクタリングする方法はありますか?
そもそも型引数がある理由はTDelegate
、メソッドのシグネチャと戻り値の型に関係なくこれを使用したいからであり、入力引数の数と、問題のメソッドが avoid
か関数かTDelegate
によって、変化。テストするメソッドへの入力引数の数ごとに異なる実装をしたくありません...
更新:
Jay がコメントで指摘しているTDelegate
ように、 の呼び出しで型引数を指定する必要はないようHasAttribute<>
です。コードは次のようになります。
Expression<Func<AccountController, LogInModel, string, ActionResult>> mut = (c, m, s) => c.LogIn(m, s);
mut.HasAttribute<ExportModelStateAttribute>().ShouldBeTrue();
ずっと良くなりましたが、それでも最初の行はかなり厄介だと思います。それはさらに良いでしょうか?