Kan ikke læse felter via fieldinfo
Hej jeg har følgende kode:using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Type t = typeof(test1);
object[] a = t.GetCustomAttributes(typeof(DocumentAttribute), false);
foreach (object att in a)
{
DocumentAttribute d = (DocumentAttribute)att;
Console.WriteLine("{0} {1}", d.Info, d.Count);
}
MethodInfo[] mi = t.GetMethods();
foreach (MethodInfo m in mi)
{
object[] o = m.GetCustomAttributes(false);
foreach (object ma in o)
{
DocumentAttribute d = (DocumentAttribute)ma;
Console.WriteLine("{0}", d.Info);
}
}
FieldInfo[] fi = t.GetFields();
foreach (FieldInfo f in fi)
{
object[] o = f.GetCustomAttributes(false);
foreach (object ma in o)
{
DocumentAttribute d = (DocumentAttribute)ma;
Console.WriteLine("{0}", d.Info);
}
}
ConstructorInfo[] ci = t.GetConstructors();
foreach (ConstructorInfo info in ci)
{
object[] o = info.GetCustomAttributes(false);
foreach (object ma in o)
{
DocumentAttribute d = (DocumentAttribute)ma;
Console.WriteLine("{0}", d.Info);
}
}
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method |
AttributeTargets.Constructor | AttributeTargets.Field,
AllowMultiple = false)]
public class DocumentAttribute : System.Attribute
{
string info;
int cnt;
public DocumentAttribute(string i)
{
info = i;
}
public int Count
{
get
{
return cnt;
}
set
{
cnt = value;
}
}
public string Info
{
get
{
return info;
}
}
}
[Document("Class test1: created for testing custom attributes", Count = 2)]
class test1
{
[Document("i: Counter variable")]
int i = 0;
[Document("Ctor test1: zero-argument ctor")]
public test1()
{
}
[Document("increment( ): Increments counter")]
public void increment()
{
i++;
}
[Document("decrement( ): Decrements counter")]
public void decrement()
{
i--;
}
}
}
Hvis du kører den vil du se at attributten for feltet "int i = 0" ikke bliver udskrevet.
Fanger jeg den forkert?