Why can't I do Class.GetMethod(string)
but I can do this.GetType().GetMethod(string)
?
I want to do the former because it seems like it would be a lot quicker since I already know what class I want to search in...
GetMethod
is a method declared on the Type
class... not on the class you're looking at. (In particular, that class could also have a GetMethod
method, which would confuse things significantly...)
You can use
typeof(Class).GetMethod(...)
though, rather than getting the type of a specific instance - is that all you were looking for?
EDIT: Note that GetType(string)
is only declared on Type
and Assembly
(and perhaps some other types). The normal Object.GetType()
method doesn't have a string parameter.
Because the former is how you would call a static method on the class.
If you want to get the type of a class, just use typeof
:
typeof(Class).GetMethod(someString);
Well, you can do either:
typeof (MyClass).GetMethod("MyMethod");
or
MyClass myClass = new MyClass();
myClass.GetType().GetMethod("MyMethod");
Just to add - myClass.GetType().GetMethod("MyMethod")
- Is resolved at runtime, where typeof(MyClass).GetMethod("MyMethod")
at compile time.
Here is a bit more on it.