views:

313

answers:

3

I am building a basic profiler for an open source project. One requirement is to measure execution time of a method. While this is easy enough, I have to do it without knowing the method or its containing class until runtime. The way to invoke the profiler will be when the user will invoke the profiler from the IDE in an active document. So if class1 is open and the user right clicks on the whitespace in the document, selects profile, then, and only then, is the class is known.

I have this code to use MethodInfo:

MethodInfo methodInfo = typeof(t).GetMethod(s);

T is just a generic type holder (class X where T : class, is the class signature). s is just a string of the method name.

I have this error, however:

Type name expected, but parameter name found.

The containing method of that line of code has t as a parameter of type T, but moving that out doesn't fix the issue. T is just an object, and if I provide an object name, like the class name, there is no error.

What gives?

EDIT: Maybe an activator can solve this.

Also, could I use the where clause to restrict T to be a static class only?

Thanks

+1  A: 

Maybe you need

t.GetType().GetMethod(s)
Justice
+2  A: 

The error is caused because typeof expects a type name or parameter like typeof(int) or typeof(T) where T is a type parameter. It looks like t is an instance of System.Type so there is no need for the typeof.

Do you need a generic type for this? Will this not work?

public void DoSomething(object obj, string methodName)
{
  MethodInfo method = obj.GetType().GetMethod(methodName);
  // Do stuff
}

or

public void DoSomething(Type t, string methodName)
{
  MethodInfo method = t.GetMethod(methodName);
  // Do stuff
}

Also, there is no way to limit a type parameter to a static class. I'm not sure what use that would be as you cannot have an instance of it and it won't be able to implement any interfaces you can use in a generic method.

Andrew Kennan
A: 

public void DoSomething(object obj, string methodName) { MethodInfo method = obj.GetType().GetMethod(methodName); // Do stuff }

This has done the trick (Same as 2 posts above).

Thanks guys!

dotnetdev