繁体   English   中英

C#引用属性的类的名称

[英]C# Name of class that references a property

无论如何传递一个对象并获取包含它的引用的对象?

例:

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

这里的代码是愚蠢的。 但我将用于在Windows窗体解决方案中简化DataBinding。

这是我将使用它的地方:

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

原因是该功能有点多余:

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

我问为了简化它:

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

那么......发生这种情况的机会是什么? 或者有一种我不知道的更简单的绑定方式?

无论如何传递一个对象并获取包含它的引用的对象?

不,一般而言。 如果您正在使用调试器API, 可能有一些方法可以执行此操作,但用于调试目的。 您的生产设计不应该要求它。

您可以使用表达式树来代替:

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

...从表达式树中找出原始对象和它正在使用的属性。

无论如何传递一个对象并获取包含它的引用的对象?

不,它不可能作为内置功能。 您必须在代码中构建它。 对象本身并不了解指向它的引用。 这是一项GC职责,需要对此进行跟踪。

暂无
暂无

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

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