C#在方法名上写个特性注释 然后拦截器中获取
时间: 2024-03-05 21:51:44 浏览: 24
您好,根据您的问题我做了如下回答:
在C#中,可以使用Attribute特性来对方法进行注释。例如:
```csharp
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class MyAttribute : Attribute
{
public string Comment { get; set; }
public MyAttribute(string comment)
{
Comment = comment;
}
}
```
上面的代码定义了一个MyAttribute特性,它可以用来对方法进行注释,并且只能应用到方法上。现在,我们可以在方法上使用这个特性:
```csharp
public class MyClass
{
[My("这是一个测试方法")]
public void TestMethod()
{
Console.WriteLine("TestMethod called.");
}
}
```
在上面的代码中,我们使用了My特性,并给它传递了一个字符串参数,这个字符串就是我们要注释的内容。
接下来,我们可以使用拦截器来获取这个特性的信息。例如:
```csharp
public class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var method = invocation.Method;
var attribute = method.GetCustomAttribute<MyAttribute>();
if (attribute != null)
{
Console.WriteLine($"方法 {method.Name} 的注释是:{attribute.Comment}");
}
invocation.Proceed();
}
}
```
在上面的代码中,我们实现了一个MyInterceptor拦截器,并在它的Intercept方法中获取了被拦截方法的My特性,并打印了它的注释内容。注意,这里使用了反射来获取特性信息。
最后,我们可以在程序中使用这个拦截器:
```csharp
var myClass = new MyClass();
var proxyGenerator = new ProxyGenerator();
var proxy = proxyGenerator.CreateClassProxyWithTarget<MyClass>(myClass, new MyInterceptor());
proxy.TestMethod();
```
在上面的代码中,我们使用了Castle.Core库中的ProxyGenerator来生成一个代理对象,并将MyInterceptor作为拦截器传递给它。然后,我们调用了这个代理对象的TestMethod方法。当TestMethod被调用时,MyInterceptor就会拦截它,并获取它的My特性信息。