Attributes in C#

前端 未结 8 738
时光说笑
时光说笑 2020-11-30 04:08

I know that C# (and .NET in general) is big on attributes. However, despite the fact I have programmed in C# for many years, I haven\'t found myself ever using them. Would s

8条回答
  •  既然无缘
    2020-11-30 04:22

    Attributes are a form of declarative programming, 'similar' to creating your UI in XAML. It 'marks' pieces of code (classes, methods, properties, whatever) with an attribute so that you can later gather all those pieces marked in a specific way and then do something standard with all of them.

    Eg. Consider the scenario where you have certain sections of code that you want to run once each time your app starts. In one model of programming (non-attribute) you go to your main method and explicitly call those init methods. With attributes you simply gather all methods which you've marked with your 'init' attribute, and call them via reflection.

    The same pattern holds for actions like serialization, persistence and whatnot...

提交回复
热议问题