您将如何制作将代码注入C#类或方法的自定义属性?

发布于 2025-02-06 15:11:51 字数 918 浏览 1 评论 0原文

我最近一直在学习C#和WPF,并一直看到人们使用属性“注入”或修改类似的类或方法的代码,我想知道如何/是否有可能使用自定义进行类型的东西属性:

这是一个较旧的示例,说明来自Nuget软件包(FodyWeavers)的属性如何通过自动提高属性换事事件来缩短代码,而当属于类中的任何属性的设置器被称为:

[ImplementPropertyChanged]
public MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    public string MyProperty { get; set; }
}

没有属性,则必须看起来像:

public MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    private string myProperty;
    public string MyProperty
    {
        get { return myProperty; }

        set
        {
            myProperty = value;
            PropertyChanged(this, new PropertyChangedEventArgs());
        }
    }
}

我在网上看的任何地方,我都会不断遇到同一个砖墙,说“自定义属性只是元数据,没有外部代码就无能为力”。我的问题是,将此外部代码放置在哪里,以便可以识别并采取属性?此外部代码是什么样的,以便可以使用这种功能?仅凭自定义属性和反射即可,这甚至可能是可能的,还是我缺少的幕后还有其他东西?

谢谢。

I've been learning C# and WPF lately and keep seeing people using attributes to "inject" or modify code inside of a class or method like this and I'm wondering how/if it is even possible to make something of the sort using custom attributes:

Here is an older example of how an attribute from a NuGet package (FodyWeavers) shortens code by automatically raising the PropertyChanged event when any setter belonging to a public property in the class is called:

[ImplementPropertyChanged]
public MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    public string MyProperty { get; set; }
}

Without the attribute, this would have to look like:

public MyClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    private string myProperty;
    public string MyProperty
    {
        get { return myProperty; }

        set
        {
            myProperty = value;
            PropertyChanged(this, new PropertyChangedEventArgs());
        }
    }
}

Everywhere I look online I keep running into the same brick wall saying "custom attributes are just metadata and do nothing by themselves without external code". My question is, where is this external code placed so that attributes can be recognized and acted upon? What would this external code look like so that such functionality is possible? Is this even possible with custom attributes and reflection alone or is there something else behind the scenes that I'm missing?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文