在c#中命中多个属性的方法

Way to hit multiple attributes in c#

在此之后: Custom Attribute not being hit 我正在寻找在我的应用程序中命中方法属性的方法。

目前据我所知是否有一些自定义属性,例如

 [AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    public MyAttribute()
    {
        Console.WriteLine("Hello");
    }
}

以及用 MyAtrtribute 修饰的方法,例如:

[MyValidation]
public class Service
{
    [MyValidation]
    public bool GetService(int id)
    {
        if (id > 100)
        {
            return true;
        }
        return false;
    }
}

触发此属性的方法是调用方法 service.GetType().GetCustomAttributes(false)。 问题是:如果我想在很多方法中装饰很多类 应用属性的方式是什么?就我而言,我想在获取 createProject()、createUser() 等方法调用时应用许可证验证。

这样的编码方式service.GetType().GetCustomAttributes(false)好像太繁琐了。 我想要一些中心位置来负责触发应用的属性。有一些优雅的解决方案吗? 谢谢!

你想要的是 AOP(面向方面​​的编程),因为现在,如果你需要自己手动调用属性,那么它们就没有价值了。您也可以调用该方法,而不是将其放入属性中。

Google AOPC# 并且您会找到一些提供程序。

印象最深的大概是PostSharp。但这也是需要花钱的。其他免费。