我怎么知道某些方法是否调用了 c# 中的特定属性

How can I know if some method has called that has a specific attribute in c#

class SampleClass 
{
    [SampleAttribute]
    public void SampleMethod() 
    {
        
    }
}

如果有类似上面代码的方法。我怎么知道调用的方法具有特定属性(在这种情况下属性是'SampleAttribute')?我知道如何找到具有特定属性的方法。但我不知道如何确定具有特定属性的方法何时调用

您可以通过几种方式完成。但首先,让我们向 SampleAttribute 添加一些值,以确保一切正常:

[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public class SampleAttribute : Attribute
{
    public SampleAttribute(string text)
    {
        Text = text;
    }

    public string Text { get; private set; }
}

并将属性值指定给方法:

public class SampleClass
{
    [SampleAttribute("This is attribute text")]
    public void SampleMethod() { }
}

现在,利用反射机制,我们可以从对象中提取属性值:

var sampleClass = new SampleClass();
ExtractSampleAttributeValue(sampleClass);

private static string ExtractSampleAttributeValue(SampleClass sampleClass)
{
        var methods = sampleClass.GetType().GetMethods();
        var sampleMethod = methods.FirstOrDefault(method => method.Name == nameof(sampleClass.SampleMethod));
        var sampleAttribute = Attribute.GetCustomAttribute(sampleMethod, typeof(SampleAttribute)) as SampleAttribute;
        return sampleAttribute.Text;
}

或者甚至将方法作为参数传递:

var sampleClass = new SampleClass();
ExtractSampleAttributeValue(sampleClass.SampleMethod);

 private static string ExtractSampleAttributeValue(Action sampleMethod)
 {
        var sampleAttribute = Attribute.GetCustomAttribute(sampleMethod.Method, typeof(SampleAttribute)) as SampleAttribute;
        return sampleAttribute.Text;
 }