How can I find my method "button_Click" by name? If I make it public, it works, but I would rather have it private.
class Test : BaseTest
{
public Test()
{
LoadMethod();
}
}
class BaseTest
{
public void LoadMethod()
{
//WHY IS THIS NULL???
var eventMethod = GetType().GetMethod("button_Click", BindingFlags.NonPublic | BindingFlags.Instance);
}
void button_Click(object sender, EventArgs e) { }
}
Why is
GetMethod
returning null?
Because the run-time type isn't of type BaseTest
, it's of type Test
, and Test
doesn't define a method called button_Click
(as it is private
in your base class).
If you'd split the GetType()
call and run your debugger, you'll see that the returned type is of type Test
.
If you call GetType().BaseType
, then you actually look at BaseTest
:
var baseType = GetType().BaseType;
if (baseType != null)
{
var eventMethod = baseType.GetMethod("button_Click", BindingFlags.NonPublic |
BindingFlags.Instance);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.