简体   繁体   中英

How to fetch object name using reflection in .net?

In .net how do I fetch object's name in the declaring type. For example...

public static void Main()
{
Information dataInformation =  new Information();
}

public class Inforamtion
{

//Constructor
public Inforamtion()
{

//Can I fetch name of object i.e. "dataInformation" declared in Main function
//I want to set the object's Name property = dataInformation here, because it is the name used in declaring that object.
}

public string Name = {get; set;}
}

As far as the CLR goes, there's not really a way to determine an object's name. That sort of information is stored (to some extent) in the debugging information and the assembly, but it's not used at runtime. Regardless, the object you're referring to is just a bunch of bytes in memory. It could have multiple references to it with multiple names, so even if you could get the names of all the variables referencing the object, it would be impossible to programmatically determine which one you're looking to use.

Long story short: you can't do that.

That is the variable name, not the object name. It also poses the question: what is the name here:

Information foo, bar;
foo = bar = new Information(); 

You can't do this for constructors etc; in limited scenarios it is possible to get a variable name via Expression , if you really want:

    public static void Main()
    {
        Information dataInformation =  new Information();
        Write(() => dataInformation);
    }
    static void Write<T>(Expression<Func<T>> expression)
    {
        MemberExpression me = expression.Body as MemberExpression;
        if (me == null) throw new NotSupportedException();
        Console.WriteLine(me.Member.Name);
    }

Note that this relies on the capture implementation, etc - and is generally cheeky.

I don't think this is possible.

But at the first place, why do you need something like this??

With my experience i have realized that if you need something weird from a compiler or a language which is not offered, then (most often) it means that there is something wrong with the approach or the logic.

Please reconsider why are you trying to achieve this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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