mardi 3 mai 2016

How to find whether a property has compiler-generated backing field? [duplicate]

This question already has an answer here:

I have a scenario where I have to find out whether a specific property represented by a PropertyInfo has a compiler generated backing field. I need this information to know if a property is "clearly" computed.

I cannot simply use the GetSetMethod(true) != null condition, because C# 6 introduced getter-only properties, which seems to give null, but still I cannot treat them as computed.

For example

public class Test {

  public bool A { get; set; } // has a backing field, should give computed = false
  public int B { get; private set; } // has a backing field,should give computed = false
  public int C { get; } // has a backing field,should give computed = false;
  public bool D { get { return B + C > 10; } } // doesn't have backing field, should give computed = true 

  private int _e = 1;
  public int E { get { return _e; } } // has an explicit backing field, so in this sense it should give computed = true

  public Test() {
    B = 3;
    C = 5;
  }
}

I'd like to write a small extension method, like this

public static bool IsComputed(this PropertyInfo propertyInfo) {
  ...
}

EDIT

Just to be more clear, before C# 6, I used the simple GetSetMethod(true) == null condition to treat a property "computed". But now the getter-only properties (which are sometimes used as an alternative to private getters) are messing it up, because they give null as they don't have set method, BUT they shouldn't be treated as computed.





Aucun commentaire:

Enregistrer un commentaire