What is the purpose of Attributes in C#?
How do I know which attribute have to use for particular functionality?
How can I add them dynamically in c#?
- 开发者_如何学Go
What are custom attributes ?
Attributes are meant to add additional information about a class, function, etc. Compilers sometimes do special things when they see an attribute. Other attributes are looked at by libraries while the program is running.
Start by looking at the documentation for the functionality you want. It should list what attributes are necessary.
No. Attributes can only be applied before the code is compiled.
That is just an attribute you created yourself as opposed to one that came with .NET.
When you write your code you answer the "what?" question:
- what to do? (methods)
- what to store? (fields and properties)
- what is what? (class hierarchies)
etc. Attributes add another dimension to this question. They answer the "how?" question. And the reply to the "how?" question may be important for IDE,
[Browsable(false)]
public string NotImportantField { get; set; } // property which will not be displayed in VS
for the compiler
[ThreadStatic]
private static RequestContext context; // field which will be different for every thread
or for another code which analyzes yours via reflection.
[XmlIgnore]
public string NotSerializableField { get; set; } // property which will not be xml-serialized
you might want to define custom attributes, if your assemblies, classes, fields, methods, etc. will be analyzed or invoked via reflection (which is often the case for example with inversion of control containers and aspect-oriented programming). Such attribute might (and often are the only way to) instruct the invoker or analyzer to behave differently depending on such attribute presence or its properties.
About your first question, well, how we know which method to call for a particular result? One of the advantages of being a .NET developer is that everything is documented pretty thoroughly. :)
Attributes are used for a Declarative Programming Model.
Attributes don't force any functionality (unless out of the box). For out-of the box attributes read up the documentation on msdn. For your own attributes you need to write code on what do if a class/method etc. has an attribute.
I don't think attributes are added dynamically. They're read dynamically though. They are metadata so are added at compile-time. Check this: Can attributes be added dynamically in C#?
Custom attributes are those that you create and tag your classes with. To create an attribute you need to create a class (for the attribute) that inherits from System.Attribute. Check this: http://msdn.microsoft.com/en-us/library/sw480ze8.aspx
Attributes are used for meta-programming. meta-programming helps you achieve dynamism with your code at runtime. Say you have 10 props in your class and you want to read only some specific props for some reason, to do this you will apply some special attributes to those props and at runtime, via reflection you will ask to filter only those props with given special attributes and then perform your job on those props. This is just one example.
In our case, we have attribute driven validation framework. so if want a prop. to be not left empty before the object is saved into database, we will mark it as NotNullOrEmpty attribute and the base class will have a method Validate() which will be called before saving the object to the database. The Validate() method will filter obj. props. with Validatable attributes and perform validation and throw exception in case validation is violated.
Attributes are used to provide meta data about your classes and methods, properties, and events inside your classes.
Some of the most common attributes are used to tell the Designer information about properties in classes, such as Browsable
and Description
. This meta-data is then used by the PropertyGrid. Other examples of attributes would be the Serializable
or Obsolete
attributes used during serialization or to mark code elements as obsolete.
You can add attributes to classes, properties, methods, and events by using the [AttributeName(parameter1,...)] syntax.
Custom attributes refer to attributes that derive from System.Attribute that are not standard attributes in the .NET framework.
Attributes are often used when setting different environment such as DEBUG, DEV, STAGING, PROD, Etc.
[Conditional("DEBUG")]
private void OutputDebugInfo()
{
WriteLine("***DEBUG MODE ***");
}
Attributes are used when you want to specify certain kind of constrains to your programming statements:
Exapmple:
[StructLayout(LayoutKind::Sequential)]
value struct Point
{
public:
int x;
int y;
};
Above you are defining that the structure should be a sequential one.
Another example is:
[DllImport("user32.dll",CallingConvention=CallingConvention::StdCall)]
Here you are specifying to import a dll using DLLImport by using attributes. I hope you are able to find out what is the purpose of attribute.
Now how to know which attributes to be used when and which functionality is the same as How you learnt Function, Delegate and Events ...by the course of time and using it. Also many people might have answered the same for you.
If you want a very usable example of where attributes can be useful, and how to do the reflection code to access them, check Enum ToString. Using that code, it becomes easy to bind a ComboBox to your enum to have typesafe choices, as well as pretty human-readable descriptions:
public static void ComboItemsFromEnum<EnumType>(ComboBox combobox) where EnumType : struct
{
combobox.FormattingEnabled = true;
foreach (object enumVal in System.Enum.GetValues(typeof(EnumType)))
{
combobox.Items.Add(enumVal);
}
combobox.Format += delegate(object sender, ListControlConvertEventArgs e)
{
e.Value = GetDescription<EnumType>(e.Value);
};
}
精彩评论