如何使用C#代码列出.Net Standard项目中.NetStandard库中的所有命名空间

问题描述 投票:0回答:1

如何使用C#代码从.Net Standard项目中列出.NetStandard Library 2.0中的所有命名空间。

这是在netStandard库中赋予Namspaces为0的代码;

            foreach (AssemblyName fooAssemblyName in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
            {
                Assembly assembly = Assembly.Load(fooAssemblyName.FullName);
                var namespaces = assembly.GetTypes()
                    .Select(t => t.Namespace).Where(t => !string.IsNullOrEmpty(t))
                    .Distinct();
                int count = namespaces.Count();
                if (fooAssemblyName.Name == "netstandard")
                {
                    Console.WriteLine(count); // THIS GIVES 0 for .Net Standard Library
                }
            }
c# .net-assembly .net-standard-2.0
1个回答
0
投票

以下行:

Assembly.GetExecutingAssembly().GetReferencedAssemblies()

如果您从该程序集中实例化了至少一个对象,则只会返回对该netstandard程序集的引用,即,即使您已为该项目添加了引用但从未使用过,它也不会出现在列表中。

[在运行代码之前尝试实例化对象,例如如果程序集中有一个名为Class1的类,则代码如下:

using System;
using System.Reflection;
using System.Linq;
using netstandard;

namespace SomeNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            var class1 = new Class1();

            foreach (AssemblyName fooAssemblyName in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
            {
                Assembly assembly = Assembly.Load(fooAssemblyName.FullName);
                var namespaces = assembly.GetTypes()
                    .Select(t => t.Namespace).Where(t => !string.IsNullOrEmpty(t))
                    .Distinct();
                int count = namespaces.Count();

                if (fooAssemblyName.Name == "netstandard")
                {
                    Console.WriteLine(count);
                }
            }
            Console.ReadLine();
        }
    }
}

Assembly

© www.soinside.com 2019 - 2024. All rights reserved.