C# Attribute parameter
In this chapter you will learn:
Positional vs. Named Parameters
A positional parameter is linked by its position. Positional parameters must be specified in the order in which they appear. Named parameters are specified by assigning values to their names. For an attribute, you can also create named parameters. named parameters can be assigned initial values by using their names. A named parameter is supported by either a public field or property, which must not be read-only.
Here is the general form of an attribute specification that includes named parameters:
[attrib(positional-param-list, named-param1 = value, named-param2 = value, ...)]
Named attribute parameter
The following code uses a named attribute parameter to passin value to an attribute.
using System; /*w w w .j a v a 2 s.co m*/
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute {
public string remark;
public string supplement;
public MyAttribute(string comment) {
remark = comment;
supplement = "None";
}
public string Remark {
get {
return remark;
}
}
}
[MyAttribute("This class uses an attribute.",
supplement = "This is additional info.")]
class UseAttrib {
}
class MainClass {
public static void Main() {
Type t = typeof(UseAttrib);
Console.Write("Attributes in " + t.Name + ": ");
object[] attribs = t.GetCustomAttributes(false);
foreach(object o in attribs) {
Console.WriteLine(o);
}
// Retrieve the MyAttribute.
Type tRemAtt = typeof(MyAttribute);
MyAttribute ra = (MyAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.Write("Remark: ");
Console.WriteLine(ra.remark);
Console.Write("Supplement: ");
Console.WriteLine(ra.supplement);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: