所以我有一个扩展方法,允许我在执行操作时记录一些内容。实现是这样的:
public static Action Log(this Action action, string log) {
return (() => {
Console.WriteLine(log);
action();
});
}
但我想允许操作也是一个 Action<T>
.有没有办法概括这一点,以便 log
被记录,但它不会更改操作的签名?
或者我需要 2 种方法,一种用于 Action
和一个 Action<T>
?
最佳答案
您需要单独的方法,但您可以根据另一个来实现一个以减少代码重复:
鉴于您现有的 Log(Action action, string log)
,您可以添加:
public static Action<T> Log<T>(this Action<T> action, string log) {
return t => Log(() => action(t), log);
}
或者反过来:
public static Action<T> Log(this Action<T> action, string log) {
return t => {
Console.WriteLine(log);
action(t);
});
}
public static Action Log(this Action action, string log) {
return () => Log<object>(t => action(), log);
}
关于c# - 有没有办法概括 Action 和 Action<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37482894/