有一个方法如:private void methodA()
{
方法开始时间 DateTime.Now;//逻辑运算方法结束时间 DateTime.Now;//方法一共使用的时间
结束时间-开始时间
}现在需要对很多方法进行写日志.每一个方法都需要计算开始时间和结束时间。怎么才能重构一个
方法出来,让逻辑运算以外的独立出来.
谢谢了..
{
方法开始时间 DateTime.Now;//逻辑运算方法结束时间 DateTime.Now;//方法一共使用的时间
结束时间-开始时间
}现在需要对很多方法进行写日志.每一个方法都需要计算开始时间和结束时间。怎么才能重构一个
方法出来,让逻辑运算以外的独立出来.
谢谢了..
{
方法开始时间 DateTime.Now;todo();方法结束时间 DateTime.Now;//方法一共使用的时间
结束时间-开始时间}调用:
定义一个方法:
void dosth()
{
//逻辑运算
...
}
调用,传入方法
methodA(dosth);
private int MethodA()
{}
private DateSet MethodB()
{}还有int,xml之类的,那是不是需要很多个委托?
watch.Start();
//方法watch.Stop();
Console.WriteLine("执行时间为:{0}秒", watch.ElapsedMilliseconds / 1000.0f);
不仅有Action(in T),Action(T1,T2.......)还有func(in T,out t)
如果要用委托的话,写死人了,还不如楼主的代码方便;
2.楼主参照7楼的写法,不要把不属于方法本身职责的处理写在方法中;
3.如果楼主有勇气颠覆一下整个开发方式
可以考虑统一描述方法,也就是对象化方法,比如这样:
public interface IMethod{
public Collection<MethodParam> Params;
public string uid;
public string Name;
public object Execute();
}
但是这种思路,对于主要靠手工编写代码的开发者也很难实施
几百个方法都需要写同样的代码.手工编码,如果哪天需要修改的话,就快不想活了..
Func<T1, T2, T3> (考虑协变和逆变,应该是 Func<in T1, in T2, out T3>),可以涵盖所有两个参数的方法,比如
int foo1(string x, double y) => Func<string, double, int>
string foo2(string x, string y) => Func<string, string, string>
string[] split(string source, char splitter)
=> Func<string, char, string[]>
...
以此类推
public class Swatch : IDisposable { public Swatch() {
w = new Stopwatch();
w.Start();
} public Swatch(SwatchCompletedHandler handler)
: this() {
this.handler = handler;
} public Swatch Enable(bool enable = true) {
this.enable = enable;
return this;
} public void Dispose() {
w.Stop();
if (handler != null && enable) { handler(w.Elapsed); }
} private bool enable;
private SwatchCompletedHandler handler;
private Stopwatch w;
}public delegate void SwatchCompletedHandler(TimeSpan elapsed);
调用如下,using (new Swatch(t => MessageBox.Show(t.ToString())).Enable()) {
Load();
}
代码可以这里下载,http://nonocast.cn/using-stopwatch/May it helps.
{
Stopwatch time = new Stopwatch();
time.Start();
method();
time.Stop();
Console.WriteLine(time.Elapsed.TotalSeconds);
}
public static valueType doMethod<valueType>(Func<valueType> method)
{
Stopwatch time = new Stopwatch();
time.Start();
valueType value = method();
time.Stop();
Console.WriteLine(time.Elapsed.TotalSeconds);
return value;
}
string upper = "ABC", lower = doMethod(() => upper.ToLower());
string numberString = "123";
int number = 0;
if (doMethod(() => int.TryParse(numberString, out number)))
{
List<int> list = new List<int>();
doMethod(() => list.Add(number));
doMethod(list.Clear);
}只是演示一下,除非是临时性的,个人不建议这样使用。如果出现这种应用,应该考虑一下重新设计底层了。
LZ可以去找找微软企业库。