简体   繁体   English

如何在类内部获取对象的变量名?

[英]How to get variable name of object inside class?

I have class A which stores ref to object B in BObject variable. 我有一个类A ,它在BObject变量中存储对对象B引用。

public class A
{
    public B BObject;
}

I want to get BObject ( name of variable ) in B class constructor. 我想在B类构造函数中获取BObject (变量的名称)。

Is there any way to do this ? 有什么办法吗?

Purpose of doing it: I want to create ODBCFramework and I want to get Table Name based on Variable Name. 这样做的目的:我想创建ODBCFramework并且要基于变量名获取表名。 ( Like in EntityFramework Context ) (就像在EntityFramework上下文中一样)

Update: I want to handle it in C#5. 更新:我想在C#5中处理它。

You can use C#-6 nameof operator : 您可以使用C#-6 nameof运算符

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

Note that generally attempting to relay on a run-time name of a property/field for table lookup seems like a bad idea. 请注意,通常尝试中继属性/字段的运行时名称以进行表查找似乎是个坏主意。

There is no way to do what you want. 无法做您想做的事。

You cannot find the name of whatever it is that is storing the reference to your object, that information is simply not available. 您找不到存储对象引用的名称,该信息根本不可用。

Basically, this: 基本上,这是:

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

is not possible. 不可能。 The fact that you have stored it in a field of another object changes nothing, it simply cannot be done. 您已经将其存储在另一个对象的字段中的事实并没有改变,这根本无法完成。

You need to have a way to explicitly tell that object which table name it should use. 您需要一种方法来明确告知该对象应使用的表名。

Can you use the PropertyInfo class? 您可以使用PropertyInfo类吗?

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

@Damien_The_Unbeliever give me some points to solve my problem. @Damien_The_Unbeliever给我一些解决问题的方法。 And I tried this, and it works. 我试过了,而且行得通。

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;
    }
}

Also, to be clear in answer: @Yuval Itzchakov suggested that in C#6 solution is: 另外,要明确答案:@Yuval Itzchakov建议在C#6中解决方案是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM