Question

given is the following class structure:

public class A{
  [MyAttribute1]
  public string field;
}
public class B : A{
  [MyAttribute2]
  [MyAttribute3]
  public string field;
}

By Reflection now I'm trying to find out if the field has the attribute "MyAttribute2" or not. But i get the following output:

foreach (FieldInfo field in TypeOfB.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
  Console.Write(field.DeclaringType);
  Console.Write(" : ");
  Console.Write(field.GetCustomAttributes(false).Length);
  Console.Write("\n");
}

//Output:
A.field : 1
B.field : 2

The expected output is:

B.field : 3

Now the question. Can any one explain why I get "field" two times and not combined? And above all, who can tell me how I'm doing it right?

Était-ce utile?

La solution

Fields can't be virtual/overriden, you have only hidden the field. Your code is equivalent to using the 'new' keyword to be more explicit about the hiding:

public class A
{
    [MyAttribute1]
    public string field;
}
public class B : A
{
    [MyAttribute2]
    [MyAttribute3]
    public new string field;
}

Properties (and methods) can be virtual/overriden:

public class A
{
    [MyAttribute1]
    public virtual string field { get; set; }
}
public class B : A
{
    [MyAttribute2]
    [MyAttribute3]
    public override string field { get; set; }
}

Autres conseils

Be careful. This field is in no way overriding the base class field. It's adding a new one; that's why you see both fields being found by reflection.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top