cxe2v
ONLINE

cxe2v

V2EX 第 39422 号会员,加入于 2013-05-21 11:45:53 +08:00
根据 cxe2v 的设置,主题列表被隐藏
二手交易 相关的信息,包括已关闭的交易,不会被隐藏
cxe2v 最近回复了
19 小时 47 分钟前
回复了 Duanye7X24 创建的主题 生活 中年以后是不是只有烟,酒才是最忠实的朋友
烟,致癌,生命缩短
酒,致癌,生命缩短
摩托车,费钱,容易出事故死了,生命大幅缩短
钓鱼,浪费生命,生命缩短
女人,浪费精力,会导致生命缩短
运动,消耗关节,会致病痛,生命质量降低
玩游戏,浪费生命
.........

总之,你做什么都会浪费生命或者导致寿命缩短,还是就安静待着吧
好像是历史上没有一起空难是因为颠簸
22 天前
回复了 loverorser 创建的主题 生活 为什么不初一初二回家过年
如果不需要在特定日子的话,为什么不现在就把家里人接过来过年
32 天前
回复了 cooco 创建的主题 职场话题 两个 offer 该怎么选呢
@cooco #7 年终这玩意最不可靠,另外,去 B 加班,钱还少了,-2 分了都
32 天前
回复了 cooco 创建的主题 职场话题 两个 offer 该怎么选呢
@cooco #5 B 不是少 2K ?你是算上了 N+2 的那个+2 了?
32 天前
回复了 cooco 创建的主题 职场话题 两个 offer 该怎么选呢
没看出 B 钱多在哪
@cxe2v

1. 定义一个自定义特性
创建一个特性类,用于标记需要记录耗时的方法:

csharp
复制代码
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public class MeasureTimeAttribute : Attribute
{
}
2. 使用动态代理拦截方法调用
通过 AOP (面向切面编程)的方式,例如使用 Castle DynamicProxy 或 DispatchProxy ,拦截方法的执行并记录耗时。

使用 DispatchProxy 示例:
csharp
复制代码
using System;
using System.Diagnostics;
using System.Reflection;

public class MethodInterceptor<T> : DispatchProxy
{
private T _decorated;

public static T Create(T decorated)
{
object proxy = Create<T, MethodInterceptor<T>>();
((MethodInterceptor<T>)proxy)._decorated = decorated;
return (T)proxy;
我一问 gpt ,代码就出来了,不比在这里问这些网友快?


}

protected override object Invoke(MethodInfo targetMethod, object[] args)
{
// 检查方法是否有 MeasureTimeAttribute
if (targetMethod.GetCustomAttribute<MeasureTimeAttribute>() != null)
{
var stopwatch = Stopwatch.StartNew();
try
{
// 执行实际方法
return targetMethod.Invoke(_decorated, args);
}
finally
{
stopwatch.Stop();
Console.WriteLine($"方法 {targetMethod.Name} 执行耗时: {stopwatch.ElapsedMilliseconds} ms");
}
}
else
{
// 没有特性直接调用方法
return targetMethod.Invoke(_decorated, args);
}
}
}
3. 应用到目标类
csharp
复制代码
public interface IExampleService
{
[MeasureTime]
void DoSomething();

void DoOtherThing();
}

public class ExampleService : IExampleService
{
public void DoSomething()
{
// 模拟耗时操作
System.Threading.Thread.Sleep(100);
Console.WriteLine("执行 DoSomething");
}

public void DoOtherThing()
{
Console.WriteLine("执行 DoOtherThing");
}
}
4. 使用动态代理包装实例
csharp
复制代码
class Program
{
static void Main()
{
var service = MethodInterceptor<IExampleService>.Create(new ExampleService());

service.DoSomething(); // 记录耗时
service.DoOtherThing(); // 不记录耗时
}
}
41 天前
回复了 v2Donuts 创建的主题 职场话题 被公司新来的前端一句话怼无语了
@stabc 你这个认知我觉得你也是个没有什么进步的后端仔
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5781 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 12ms · UTC 02:08 · PVG 10:08 · LAX 18:08 · JFK 21:08
Developed with CodeLauncher
♥ Do have faith in what you're doing.