What are attributes in .NET?

2019-01-01 04:44发布

What are attributes in .NET, what are they good for, and how do I create my own attributes?

11条回答
听够珍惜
2楼-- · 2019-01-01 05:26

An attribute is a class that contains some bit of functionality that you can apply to objects in your code. To create one, create a class that inherits from System.Attribute.

As for what they're good for... there are almost limitless uses for them.

http://www.codeproject.com/KB/cs/dotnetattributes.aspx

查看更多
倾城一夜雪
3楼-- · 2019-01-01 05:27

Attributes are like metadata applied to classes, methods or assemblies.

They are good for any number of things (debugger visualization, marking things as obsolete, marking things as serializable, the list is endless).

Creating your own custom ones is easy as pie. Start here:

http://msdn.microsoft.com/en-us/library/sw480ze8(VS.71).aspx

查看更多
时光乱了年华
4楼-- · 2019-01-01 05:27

Attributes are also commonly used for Aspect Oriented Programming. For an example of this check out the PostSharp project.

查看更多
旧人旧事旧时光
5楼-- · 2019-01-01 05:30

As said, Attributes are relatively easy to create. The other part of the work is creating code that uses it. In most cases you will use reflection at runtime to alter behavior based on the presence of an attribute or its properties. There are also scenarios where you will inspect attributes on compiled code to do some sort of static analysis. For example, parameters might be marked as non-null and the analysis tool can use this as a hint.

Using the attributes and knowing the appropriate scenarios for their use is the bulk of the work.

查看更多
初与友歌
6楼-- · 2019-01-01 05:30

To get started creating an attribute, open a C# source file, type attribute and hit [TAB]. It will expand to a template for a new attribute.

查看更多
登录 后发表回答