Attributes in C#

前端 未结 8 743
时光说笑
时光说笑 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:19

    Attributes are very good at describing some runtime behaviour of your code that is orthoganal to the code in question. For example, in a class called Customer you would model a customer, right? But you might not want to model or describe the way a Customer object is serialized.

    Adding attributes to your Customer class allows you to tell some other part of the runtime how it should deal with your Customer.

    MSTest and NUnit makes use of attributes to tell the test framework how it should use classes that define test fixtures.

    ASP.NET MVC uses attribute to tell the mvc framework which methods on classes it should treat as controller actions.

    So, any place where you have a runtime behaviour that you wish to model attributes can be useful.

提交回复
热议问题