There is a class, it has a property and a constructor

public class Pen { private int inkContainerValue = 1000; public Pen(int inkContainerValue) { this.inkContainerValue = inkContainerValue; } 

In a third-party class, I create an object of this class and I want to know what type of variable inkContainerValue how to implement it?

  • one
    And what are you going to do with this information? - andreycha
  • @andreycha Unit test. Assert.AreEqual("Тип переменной которое мы получим","Предполагаемый тип переменной" - Pavel Kushnerevich
  • @andreycha tried to do something like this Pen pen = new Pen(inkContainerValueTes); Type myType = typeof(Pen); PropertyInfo myPropInfo = myType.GetProperty("inkContainerValue"); //assert Assert.AreEqual(myPropInfo.Name, actual); Pen pen = new Pen(inkContainerValueTes); Type myType = typeof(Pen); PropertyInfo myPropInfo = myType.GetProperty("inkContainerValue"); //assert Assert.AreEqual(myPropInfo.Name, actual); , but apparently did not quite understand how PropertyInfo myPropInfo = myType.GetProperty("inkContainerValue"); Works - Pavel Kushnerevich
  • 2
    And what is the purpose of such a test? You need to test contracts, not implementation . - andreycha

1 answer 1

You do almost right. This code gets the type you need:

 var classType = typeof(Pen); var field = classType.GetField( "inkContainerValue", BindingFlags.Instance | BindingFlags.NonPublic); var fieldType = field.FieldType; 

You had to work with GetField ( inkContainerValue is a field, not a property), and specify flags that allow reflection of private fields.


Nevertheless, I join the comment @andreycha: most likely you do not need it.

  • Thank you very much. got it. - Pavel Kushnerevich
  • @PavelKushnerevich: Please! - VladD
  • There is little experience in unit testing. How to rationally test the field? Rather, not even rational, but right? - Pavel Kushnerevich
  • four
    @PavelKushnerevich: My point of view - no way. You have to test only what is in the specification. And in the specification there can be no field values; there can only be observable class behavior. - VladD