Is there any way to get a List
which contains all \'usings\' within a namespace/class?
For instance
using System;
using System
This will work for all types in methods of the declaring class, however it wont give all namespaces for all classes in the file where it was before compiling. That is impossible because after compilation the framework cannot know what was where in files.
So if you have one CLASS per file this will work: If you are missing something (i look for fields and methods, maybe something is not taken in account, if that is so just add)
List namespaces = new List();
var m = MethodInfo.GetCurrentMethod();
foreach (var mb in m.DeclaringType.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic))
{
if (mb.MemberType == MemberTypes.Method && ((MethodBase)mb).GetMethodBody() != null)
{
foreach (var p in ((MethodInfo)mb).GetMethodBody().LocalVariables)
{
if (!namespaces.Contains(p.LocalType.Namespace))
{
namespaces.Add(p.LocalType.Namespace);
Console.WriteLine(p.LocalType.Namespace);
}
}
}
else if (mb.MemberType == MemberTypes.Field) {
string ns = ((System.Reflection.FieldInfo)mb).FieldType.Namespace;
if (!namespaces.Contains(ns))
{
namespaces.Add(ns);
Console.WriteLine(ns);
}
}
}
Sample output for my case:
System
System.Collections.Generic
System.Reflection
WindowsFormsApplication2
System.Linq.Expressions