在 C# 中获取命名空间中的类列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1835665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:16:30  来源:igfitidea点击:

Get list of classes in namespace in C#

c#.netreflection

提问by AndreyAkinshin

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

我需要以编程方式获取List给定命名空间中的所有类。我怎样才能在 C# 中实现这个(反射?)?

采纳答案by Klaus Byskov Pedersen

var theList = Assembly.GetExecutingAssembly().GetTypes()
                      .Where(t => t.Namespace == "your.name.space")
                      .ToList();

回答by Wim Hollebrandse

Without LINQ:

没有 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);
}

回答by Wim Hollebrandse

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

看看这个如何获取命名空间内的所有类?提供的答案返回一个 Type[] 数组,您可以轻松修改它以返回 List

回答by Pharabus

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;
        }