是否有反正傳遞一個對象並找回包含引用的對象?C#引用屬性的類的名稱
實施例:
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 Form解決方案中的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);
那麼......發生這種情況的可能性有多大?或者有一種我不知道的更簡單的綁定方式?
呃......如果Jon Skeet說表情樹是唯一的出路,我可能會保持原樣。我已經在反思中掙扎了。甚至無法想象試圖圍繞表情樹包裹我的頭。 –