D
davearkley
I've recently 'discover' the wonders of custom attributes and
reflection. There's one aspect that has stumping me and I've been
unable to find samples in the docs or on the web.
I have fields in a class which have zero, one or more custom attributes
associated with each field. I'd like to get a list of the attributes
present for a given field, and then iterate over them to find
associated values.
Where I've coded for the presence of one attribute I've used:
FieldInfo[] Fields = TypeData.GetFields(BindingFlags.Instance |
BindingFlags.NonPublic);
foreach (FieldInfo Field in Fields)
{
if (!Attribute.IsDefined(Field, typeof(MyAttribute)))
{
Console.WriteLine(Field.Name)
}
else
{
MyAttribute TheAttribute =
(MyAttribute)Field.GetCustomAttributes(typeof(Field), false)[0];
if (0 == MyAttribute.Name.Length) Console.WriteLine(Field.Name);
else Console.WriteLine(MyAttribute.Name);
}
}
I can see how this works - I'm telling it the type of attribute
(MyAttribute) to look for. What I cant find the syntax for is to
'.GetCustomAttributes" where I don't already know the type.
Can anyone help please?
reflection. There's one aspect that has stumping me and I've been
unable to find samples in the docs or on the web.
I have fields in a class which have zero, one or more custom attributes
associated with each field. I'd like to get a list of the attributes
present for a given field, and then iterate over them to find
associated values.
Where I've coded for the presence of one attribute I've used:
FieldInfo[] Fields = TypeData.GetFields(BindingFlags.Instance |
BindingFlags.NonPublic);
foreach (FieldInfo Field in Fields)
{
if (!Attribute.IsDefined(Field, typeof(MyAttribute)))
{
Console.WriteLine(Field.Name)
}
else
{
MyAttribute TheAttribute =
(MyAttribute)Field.GetCustomAttributes(typeof(Field), false)[0];
if (0 == MyAttribute.Name.Length) Console.WriteLine(Field.Name);
else Console.WriteLine(MyAttribute.Name);
}
}
I can see how this works - I'm telling it the type of attribute
(MyAttribute) to look for. What I cant find the syntax for is to
'.GetCustomAttributes" where I don't already know the type.
Can anyone help please?