I have a simple class with a property
class Foo
{
string Title { get; set; }
}
I am trying to simplify data binding by calling a function like
BindToText(titleTextBox, ()=>foo.Title );
which is declared like
void BindToText(Control control, Expression> property)
{
var mex = property.Body as MemberExpression;
string name = mex.Member.Name;
control.DataBindings.Add("Text", ??? , name);
}
so what do I put in ???
for the instance of my Foo
class. How do I get a refernce to the calling foo
instance from the lambda expression?
edit:
Экземпляр должен быть где-то там, потому что я могу вызвать property.Compile ()
и создать делегат, который использует экземпляр foo
внутри моей функции BindToText
. Поэтому у меня вопрос: можно ли это сделать без добавления ссылки на экземпляр в параметрах функции. Я призываю Бритву Оккума дать простейшее решение.
править 2:
What many have failed to notice is the closure that exists in accessing the instance of foo
inside my function, if I compile the lambda. How come the compiler knows where to find the instance, and I don't? I insist that there has to be an answer, without having to pass an extra argument.
Thanks to VirtualBlackFox the solution is such:
void BindText(TextBoxBase text, Expression> property)
{
var mex = property.Body as MemberExpression;
string name = mex.Member.Name;
var fex = mex.Expression as MemberExpression;
var cex = fex.Expression as ConstantExpression;
var fld = fex.Member as FieldInfo;
var x = fld.GetValue(cex.Value);
text.DataBindings.Add("Text", x, name);
}
which alows me to simply type BindText(titleText, () => foo.Title);
.