Reputation: 494
i am trying to get all of my methods in all the classes with reflection. I Here is my code. I can get the class names, but i cant get the method names. How can i do that?
string @namespace = "Application.Main";
List<String> methodNames = new List<string>();
List<String> appServiceClasses = new List<string>();
List<Type> returnVal = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(t => t.GetTypes())
.Where(t => t.IsClass && t.Namespace == @namespace).ToList();
for (int i = 0; i < returnVal.Count; i++)
{
appServiceClasses.Add(returnVal[i].Name);
}
Type myTypeObj = typeof(appServiceClasses[0]);
MethodInfo[] methodInfos = myTypeObj.GetMethods();
foreach (MethodInfo methodInfo in methodInfos)
{
string a = methodInfo.Name;
}
Upvotes: 0
Views: 773
Reputation: 19230
You don't need to store the type name and then use typeof
. You already have the type:-
var appServiceClassTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.IsClass && x.Namespace == ...)
.ToList();
var appServiceClasses = appServiceClassTypes.Select(x => x.Name);
var methodNames = appServiceClassTypes.SelectMany(x => x.GetMethods())
.Select(x => x.Name)
.ToList();
If you don't actually need the appServiceClasses
collection anywhere, you should just be able to chain those together:-
var methodNames = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.IsClass && x.Namespace == ...)
.SelectMany(x => x.GetMethods())
.Select(x => x.Name)
.ToList();
You probably want to know which methods belong to which class, though:-
var methods = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.IsClass && x.Namespace == ...)
.Select(x => new Tuple<string, IEnumerable<string>>(
x.Name,
x.GetMethods().Select(y => y.Name)));
or:-
var methods = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x => x.IsClass && x.Namespace == ...)
.ToDictionary(
x => x.Name,
x => x.GetMethods().Select(y => y.Name));
Upvotes: 1
Reputation: 101731
Well, you already have the type of your classes, why you are getting name of them ? I mean what is the purpose of doing that? you can use those type instances to get your methods.
var methods = returnVal.SelectMany(x => x.GetMethods());
Edit: you can also use a Dictionary<string, MethodInfo[]>
so you can access the method so of a class with it's name like:
var methods = returnVal.ToDictionary(x => x.Name, x => x.GetMethods());
var methodsOfFoo = methods["Foo"];
Upvotes: 1
Reputation: 4628
Use the type to ask for methods:
for (int i = 0; i < returnVal.Count; i++)
{
appServiceClasses.Add(returnVal[i].Name);
MethodInfo[] methodInfos = returnVal[i].GetMethods();
foreach (MethodInfo methodInfo in methodInfos)
{
string a = methodInfo.Name;
}
}
Upvotes: 1