简体   繁体   中英

C# Name of class that references a property

Is there anyway to pass an object and get back the object that holds a reference to it?

Example:

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

    public Person(string name)
    {
        this.Name = name;
    }
}

public static class Helper
{

    public static void IsItPossible()
    {
        var person = new Person("John Doe");

        var whoKnowsMe = WhoIsReferencingMe(person.Name);

        //It should return a reference to person
    }

    public static object WhoIsReferencingMe(object aProperty)
    {
        //The magic of reflection
        return null;
    }
}

The code here is dumb. But I'll be using to simplify DataBinding in a Windows Form solution.

Here is where I'll use it:

    protected void Bind(object sourceObject, object sourceMember, 
        Control destinationObject, object destinationMember)
    {
        //public Binding(string propertyName, object dataSource, string dataMember);
        string propertyName = GetPropertyName(() => destinationMember);
        string dataMember = GetPropertyName(() => sourceMember);

        Binding binding = new Binding(propertyName, sourceObject, dataMember);

        destinationObject.DataBindings.Add(binding);
    }

    public  string GetPropertyName<T>(Expression<Func<T>> exp)
    {
        return (((MemberExpression)(exp.Body)).Member).Name;
    }

The reason is that the function is kind of redundant:

    this.Bind(viewModel.Client, viewModel.Client.Id, view.icClientId, tiew.icClientId.Text);

I ask in order to simplify it to this:

    this.Bind(viewModel.Client.Id, view.icClientId.Text);

So... any chance of this happening? Or there's a simpler way of binding that I'm unaware of?

Is there anyway to pass an object and get back the object that holds a reference to it?

No, in general. There may be ways of doing this if you're using the debugger API, but only for debugging purposes. Your production design shouldn't require it.

You could potentially use expression trees instead though:

this.Bind(() => viewModel.Client.Id, () => view.icClientId.Text);

... and work out from the expression tree both the originating object and the property that it's using.

Is there anyway to pass an object and get back the object that holds a reference to it?

No, it's not possible as built-in feature. You have to architect it in your code. Object as itself has no knowledge about references that point to it. This is a GC duty, to take trace of 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