オブジェクトを渡し、そのオブジェクトへの参照を保持しているオブジェクトを取り戻す方法はありますか?
例:
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フォームソリューションでデータバインディングを単純化するために使用します。
これが私がそれを使うところです:
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);
だから...これが起こる可能性はありますか?または、私が気付いていない、より簡単なバインド方法がありますか?