帰宅途中で私はアイデアを持っていました.Func/Action拡張を作成して、C#で素晴らしい構文糖を使用できるようにします。メソッドがfunc/action代理人のように構文的に機能しないのはなぜですか?
理論上の例...時間にメソッドの実行を、あなたを許すのFunc /アクションの様々な順列のための拡張機能を作成。
私が家に到着して例を試したとき、私はこれがおそらくないことを発見しました。私はそれがC#の欠点/不一致だと信じています。デリゲートとメソッドは同じ(理論上)のものです。
public static class Extensions
{
public static void Time(this Action action)
{
// Logic to time the action
action();
}
}
public class Example
{
public void Main()
{
Action action = RunApp;
Action actionLambda =() => { };
Action actionDelegate = delegate() { };
Extensions.Time(RunApp); // Works
Extensions.Time(() => { }); // Works
Extensions.Time(delegate() { }); // Works
Extensions.Time(action); // Works
Extensions.Time(actionLambda); // Works
Extensions.Time(actionDelegate); // Works
action.Time(); // Works
actionLambda.Time(); // Works
actionDelegate.Time(); // Works
((Action) RunApp).Time(); // Works
((Action) delegate() { }).Time(); // Works
((Action) (() => { })).Time(); // Works
// These should all be the same!
RunApp.Time(); // No good: "Example.RunApp() is a method which is not valid in the given context"
() => { }.Time(); // No good: Operator '.' cannot be applied to operand of type 'lambda expression'"
(() => { }).Time(); // No good: Operator '.' cannot be applied to operand of type 'lambda expression'"
delegate() { }.Time(); // No good: "Operator '.' cannot be applied operand of the type 'anonymous method'"
}
public void RunApp()
{
// Stuff...
}
}
私はのFunc /アクションを理解するには、デリゲートとメソッドのグループに比べてC#に新しい追加されているが、なぜそれらはすべて同じように行動することはできませんか?
アクション。タイム(あなたのコードに示すように、明示的に –
あなたの最後の行は、 '((アクション)(()=> {}))にする必要があるアクションとして何かをカプセル化するために言っている、方法をカプセル化するので、 ); ' –
別の「作品」として追加し、オリジナルをリセットします。 – smdrager