Attributes...

  • Thread starter Thread starter Jacek Jurkowski
  • Start date Start date
J

Jacek Jurkowski

Here's some code:

public enum Cars
{
[CarWidthAttribute(2540)]
[CarColorAttribute("Black")]
BMW = 1,
[CarWidthAttribute(2620)]
[CarColorAttribute("Red")]
BUICK = 2.
{

How to reflect attributes describing BMW?

Somethink like:

Cars.BMW.GetType().GetCustomAttributes();
 
You need to look at the static fields (FieldInfo), and the attributes
on them (which is how it gets implemented)

Marc
 
using System;
using System.Reflection;
public enum Cars {
[CarWidth(2540)]
[CarColor("Black")]
BMW = 1,
[CarWidth(2620)]
[CarColor("Red")]
BUICK = 2
}
class CarWidthAttribute : Attribute {
private readonly int width;
public CarWidthAttribute(int width) { this.width = width; }
public override string ToString() { return "Width = " +
width.ToString(); }
}
class CarColorAttribute : Attribute {
private readonly string color;
public CarColorAttribute(string color) { this.color = color; }
public override string ToString() { return "Color = red"; }
}
static class Program {
static void Main() {
Type dataType = Enum.GetUnderlyingType(typeof(Cars));
foreach (FieldInfo field in
typeof(Cars).GetFields(BindingFlags.Static | BindingFlags.GetField |
BindingFlags.Public)) {
object value = field.GetValue(null);
Console.WriteLine("{0}={1}", field.Name,
Convert.ChangeType(value, dataType));
foreach (Attribute attrib in
field.GetCustomAttributes(true)) {
Console.WriteLine("\t{0}", attrib);
}
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top