dimanche 12 juin 2022

How would you make a custom attribute that injects code into a class or method in C#?

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.





Aucun commentaire:

Enregistrer un commentaire