无论如何要传递一个对象并取回持有对它的引用的对象吗?
例子:
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);
所以……这有可能发生吗?还是有一种我不知道的更简单的绑定方式?