【发布时间】:2015-07-10 09:43:53
【问题描述】:
我有一个函数,它使用秒表的实例通过启动和停止来测量方法的时间。 我可以以某种方式在属性中定义该函数,然后用该属性装饰任何给定的方法来测量该方法的时间吗? 这将减少 LOC。 我不想使用任何第三方库。
public class AppTrace:BaseModel<AppTrace>
{
[DataMember]
public string Comment;
[DataMember]
public string MethodName;
[DataMember]
public DateTime StartTimeStamp;
[DataMember]
public int Duration;
[DataMember]
public int UserObjectId;
[DataMember]
public string MachineName;
[DataMember]
public int ToolId;
private System.Diagnostics.Stopwatch stpWatch;
public AppTrace(string comment,string methodName,int userObjectId ,string machineName = "",int? toolId=null)
{
MethodName = methodName;
UserObjectId = userObjectId;
StartTimeStamp = DateTime.UtcNow;
Comment = comment;
MachineName = machineName;
stpWatch = new System.Diagnostics.Stopwatch();
stpWatch.Start();
}
public AppTrace()
{
}
public void CloseTrace()
{
this.stpWatch.Stop();
Duration=Convert.ToInt32( this.stpWatch.ElapsedMilliseconds);
}
}
如果没有属性,我可以在代表的帮助下做到这一点吗?
【问题讨论】:
-
看看this thread,我想它回答了你的问题
-
不,这是不可能的。您必须编写一些方法调用实用程序,它实际上将启动和停止
StopWatch(例如Invoke.Measure(() => {/*do some stuff*/}))或改用一些AOP 框架(例如PostSharp,它在编译时使用IL 重写)。跨度> -
我正在该预定义函数中启动和停止秒表。
-
我有一个启动秒表的功能和一个停止它的功能。现在,要测量任何给定方法的时间,我必须在前后调用这两个函数。那么,为了减少 loc,我可以使用属性吗?
-
属性只能包含元信息,不能执行任何动作。而且即使你要定义这样一个属性,一些上层代码也必须通过反射找到它并以适当的方式使用。改用静态实用程序和 lambda 会更简单。
标签: c# methods attributes