lundi 27 août 2018

C# - Is it possible to retrieve the variable name (not value) of a property using reflection?

I am trying to retrieve the variable name of a property, instead of the value. I am currently using reflection, but if anyone has other suggestions it would be much appreciated.

I have three classes involved

A:

Class A {

public B bObject;

int Number{ return bObject.number;} //returns 3
}

B:

Class B {   public int number = 3; }

C:

Class C {

public void myMethod(){
A aObject = new A();
var aNumber = aObject.GetType.GetProperty("Number").GetValue(aObject, null);
//this is the value. aNumber = 3.
var objName = nameof(aNumber); //returns aNumber
}

I want objName to return the string "bObject.number," the variable that was called inside the property. Is this possible with my current setup, and if not, does anyone have recommendations?

I'd rather not have another method in B to return "nameof(bObject) + nameof(bObject.number)" then call both that method and the prop due to redundancy. Thanks for your time.





Aucun commentaire:

Enregistrer un commentaire