This question already has an answer here:
Very similar to How to get all public both get and set properties of a type
Suppose I have a simple class:
public class MyClass
{
private int A {get; set;}
public int B {get; private set;}
public int C {get; set;}
public MyClass() {... sets this.A and this.B}
}
Using reflection I want the sequence of all properties that I can write values to. The following is incorrect:
var allWritableProperties = typeof(MyClass).GetProperties()
.Where(property => property.CanWrite);
- Method GetProperties correctly returns only the public properties B and C.
- Property B has a private Set, so I can't write to it.
- Yet B CanWrite is true, therefore the Where Function will return B and C.
- I can only write to C, therefore I want only C
For those who want to know why I want to do this. I have a class with that implements IEquality. I have a unit test that tests whether this is implemented correctly. Recently someone added a property but forgot to change the Equals function. Therefore some different objects were considered to be equal. My unit test should have warned about this.
Therefore I want to change the test such that it changes all public writable properties one by one and checks if Equals returns false. In that case if someone added a public writable property but forgot to use check it in Equals the test would fail.
Aucun commentaire:
Enregistrer un commentaire