It's great. It's so beautiful. I really like it.
Reflecting types using LINQ.
How can we do it?
We can use Reflection of course, but with LINQ it shortest and simplest.
Declare "Type" object , assign the class you want to query and query with LINQ.
Example 1:
To get all methods of a class:
1: Type tPerson = typeof(Person);
2: var methods = from method in tPerson.GetMethods()
3: select method;
4:
5: Console.WriteLine("All methods:");
6: foreach (var m in methods)
7: {
8: Console.WriteLine(m.Name);
9: }
Example 2:
To get all methods that returns "int", use the "where' clause:
1: var ints = from method in tPerson.GetMethods()
2: where method.ReturnType == typeof(int)
3: select method;
4:
5: Console.WriteLine("All methods that returns int:");
6: foreach (var intType in ints)
7: {
8: Console.WriteLine(intType.Name);
9: }
No comments:
Post a Comment