我正在尝试检索属性的变量名称,而不是值。我目前正在使用反射,但如果有人有其他建议,我将不胜感激。
我涉及三个类
答:
class A
{
public B bObject;
int Number { return bObject.number; } //returns 3
}
乙:
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
}
我希望objName 返回字符串“bObject.number”,这是在属性内部调用的变量。我当前的设置是否可行,如果不行,有人有建议吗?
由于冗余,我宁愿 B 中没有其他方法返回“nameof(bObject) + nameof(bObject.number)”然后调用该方法和 prop。谢谢你的时间。
最佳答案
您在这里要做的是检索 Number 方法的主体,然后删除“return”和“;”只获得您想要的值(value)。
这里有一个很好的例子,展示了如何将方法的主体作为字符串获取: Getting a specific method source code from .cs file (at runtime)
完成后,您就可以解析出“return”和“;”得到你想要的。
这不是很优雅,但它可以满足您的需求。
关于c# - 是否可以使用反射检索属性的变量名(而不是值)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52046463/