【问题标题】:Functional Attributes C#功能属性 C#
【发布时间】:2018-07-28 20:53:25
【问题描述】:

在 C# 中,如何使用属性本身或属性作为某种形式反射的标记来注入代码?

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class AddMessage : Attribute
{
    public AddMessage()
    {
        //...
    }
}

例如,您可以使用AddMessage 来操作类似这样的自动属性

[AddMessage]
public int Count { get; set; } = 0;

为了看起来像这样的东西?

private int count;
public int Count {
    get {
        return count;
    }
    set {
        count = value;
        Console.WriteLine("Setter Message");
    }
}

//Somewhere else
count = 0;

【问题讨论】:

标签: c# properties attributes aop


【解决方案1】:

你可以试试Fody 框架。它的一般方法是在编译(“编织”)后根据在那里找到的内容修改您的程序集。我不喜欢这都是“元”而不是代码本身的一部分,但它可以完成原本不可能的事情。

Anotar 模块看起来符合您想要做的事情,否则您可能会编写自己的模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2020-09-10
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多