Today I wrote a control with its codebehind in a separate reference project. From that codebehind I needed to reference a property in the parent page as well as to call a method. Fortunately I know how to use reflection to get the job done, for the property:
private int _lid;
public int lid {
get
{
Type parentType = this.Parent.Page.GetType();
int _lid = int.Parse(parentType.InvokeMember("lid",
System.Reflection.BindingFlags.GetProperty, null, this.Parent.Page, null).ToString());
return _lid;
}
set {_lid = value;}
}
Like many .NET techniques, while I know what to use to get the job done, I can certainly use more core understanding. While I'm normally a one-line-of-code-when-possible kind a guy, I'm seeing that if I want to get that core understanding of reflection I have to simplify the syntax, even it if requires additional lines of code. It would be a similar approach to, say, learning ADO.NET.
So instead of using the original syntax above, I did some exploring and found the more simple approach below works just as well.
Type type = this.Parent.Page.GetType();
object o = type.GetProperty("lid").GetValue(this.Parent.Page, null);
int _lid = int.Parse(o.ToString());
return _lid;
After all, 95% of the time, simpler is better.