如何获取class内对象的变量名?

How to get variable name of object inside class?

我有 class A 将对象 B 的引用存储在 BObject 变量中。

public class A
{
    public B BObject;
}

我想在 B class 构造函数中获取 BObject (变量名称)。

有什么办法吗?

这样做的目的:我想创建ODBCFramework,我想根据Variable Name得到Table Name。 (就像在 EntityFramework 上下文中一样)

更新:我想在 C#5 中处理它。

您可以使用 C#-6 nameof operator:

var a = new A();
string bName = nameof(a.B);

请注意,通常尝试中继 property/field 的 运行 时间名称以进行 table 查找似乎是个坏主意。

没有办法如你所愿

您找不到存储对象引用的任何名称,该信息根本不可用。

基本上,这个:

var x = new BObject();
// from inside BObject, get the name "x"

不可能。您将它存储在另一个对象的字段中这一事实不会改变任何事情,它根本无法完成。

你需要有一种方法来明确地告诉那个对象应该使用哪个table名称。

你能用PropertyInfoclass吗?

var a = B.GetInfo().GetProperties();
foreach(PropertyInfo propertyInfo in a)
    string name = propertyInfo.Name

@Damien_The_Unbeliever给我一些积分来解决我的问题。我尝试了这个,它有效。

public class A
{
    public B BObject { get; set; }
    public A()
    {
        var BTypeProperties = this.GetType().GetProperties().Where(x => x.PropertyType == typeof(B));
        foreach (var prop in BTypeProperties)
        {
            prop.SetValue(this, new B(prop.Name));
        }
    }

}

public class B
{
    string _propName;
    public B(string propertyName)
    {
        _propName = propertyName;
    }
}

此外,要在回答中明确: @Yuval Itzchakov 建议在 C#6 中的解决方案是:

var a = new A();
string bName = nameof(a.B);