Does this C# feature have a name and what does it do?
I'm a C# newbie. Saw this piece of code in an open source
public class Staff : BusinessObjectBase
{
/// <summary>
/// Column: StaffID(Identity)(Primary Key开发者_如何学编程), Allow DBNull=False
/// </summary>
[DataMap("StaffID", IsIdentity=true, IsReadOnly=true, IsKey=true)]
public System.Nullable<System.Int32> StaffID { get; set; }
/// <summary>
/// Column: TeamID, Allow DBNull=True
/// </summary>
[DataMap("TeamID", AllowDBNull=true)]
public System.Nullable<System.Int32> TeamID { get; set; }
The lines start with open square brackets, what are they doing? reference to parent object's attributes? If so, why are they neccessry? Is there a name of this style of coding? Thank you!
This all falls under a concept known as metaprogramming. There is a book called Metraprogramming in .NET (Manning). You're basically annotating your code with data that can later be interpreted at runtime by some other code via reflection. This is popular in Java and Ruby as well. You'll see it in ASP.NET MVC, WCF, and much more. It also introduces another programming practice known as Declarative Programming. You say "what you want to do", and let something else determine "how". It's really big in functional programming languages and just programming in general for that matter. See this post about how to parse the attributes. How do I GetCustomAttributes?
Those are called attributes--see MSDN.
Read all about C# Attributes. They're basically instances of classes that attach themselves to other properties/methods/classes/code elements. In this case, put simply, you defined a new field called StaffID
of type System.Nullable<...>
that has a DataMap
object attached to it.
Data Annotations to Customize Data Classes
http://msdn.microsoft.com/en-us/library/dd901590(v=vs.95).aspx
They're attributes.
精彩评论