Get list of classes in namespace in C# [duplicate]

2020-08-23 04:10发布

I need to programmatically get a List of all the classes in a given namespace. How can I achieve this (reflection?) in C#?

4条回答
一夜七次
2楼-- · 2020-08-23 04:42

Take a look at this How to get all classes within namespace? the answer provided returns an array of Type[] you can modify this easily to return List

查看更多
你好瞎i
3楼-- · 2020-08-23 04:51

Without LINQ:

Try:

Type[] types = Assembly.GetExecutingAssembly().GetTypes();
List<Type> myTypes = new List<Type>();
foreach (Type t in types)
{
  if (t.Namespace=="My.Fancy.Namespace")
    myTypes.Add(t);
}
查看更多
祖国的老花朵
4楼-- · 2020-08-23 04:52
var theList = Assembly.GetExecutingAssembly().GetTypes()
                      .Where(t => t.Namespace == "your.name.space")
                      .ToList();
查看更多
甜甜的少女心
5楼-- · 2020-08-23 05:00

I can only think of looping through types in an assebly to find ones iin the correct namespace

public List<Type> GetList()
        {
            List<Type> types = new List<Type>();
            var assembly = Assembly.GetExecutingAssembly();
            foreach (var type in assembly .GetTypes())
            {
                if (type.Namespace == "Namespace")
                {
                    types.Add(type);
                }
            }
            return types;
        }
查看更多
登录 后发表回答