开发者

Getting the instance name of a class instance within the class

I have a class foo as such:

    class Foo
    {

    }

and I have initial开发者_JAVA技巧ized an instance as

    Foo _bar =new Foo();

How do I get the name of the variable (_bar for the purposes of this question) within the class Foo?


_bar is not a name of the instance of the class. It's a name of a variable that holds a reference to that instance. The instance doesn't know anything about what variables hold references to it, so what you want to do is impossible.

If you want your instances to have names, you would have to add a property to your class, e.g. like this:

class Foo
{
    public string Name { get; set; }
}

and use it like this:

Foo bar = new Foo { Name = "baz" };


You can include "Foo _bar =new Foo();" inside another class and then find it by reflection and then set an elementname property inside class Foo again by reflection.

class Foo
{

public string ElementName {get; set;}


}

public class MyParent
{
Foo _bar =new Foo();

public MyParent()
{
//You can find Foo(s) here and then set ElementName of Each foo by reflection
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜