C#引用属性的类的名称

时间:2012-11-27 14:03:39

标签: c# data-binding reflection

是否有传递对象并获取包含对象引用的对象?

示例:

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

那么......发生这种情况的可能性有多大?或者有一种我不知道的更简单的绑定方式?

2 个答案:

答案 0 :(得分:2)

  

是否有传递对象并获取包含对象引用的对象?

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

您可能会使用表达式树代替:

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

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

答案 1 :(得分:0)

  

无论如何都要传递一个对象并取回持有一个对象的对象   参考它?

不,它不可能作为内置功能。您必须在代码中构建它。 对象本身并不了解指向它的引用。这是GC职责,可以追踪这一点。