3

I have a simple POCO class, e.g.

class C {
  [MyAtrib]
  public int i {get; set;}
  [MyAtrib]  
  public int i2;
}

When I call:

GetType().GetFields(
  BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

on that class (instance) I can't get the FieldInfo for those members that have automatically generated getters/setters (i.e. int i above).

Actually, I'm trying to read those custom attributes (MyAtrib) and can't do it for those properties that have {get; set;}.

Why is that? I'd expect to get both i and it's (private) backing field, since i is public.

Can I get to i's MyAtrib somehow through reflection?

4

1 回答 1

9

你现在得到字段,但public int i {get; set;}它是一个属性。您需要获取属性:

// note: properties -> generally public
GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
于 2013-10-16T17:41:17.390 回答