如何获得程序集的命名空间?
考虑我有一个汇编(类库dll),我已使用以下代码加载,
Assembly a = Assembly.LoadFrom(@"C:\Documents and Settings\E454935\My Documents\Visual Studio 2005\Projects\nunit_dll_hutt\for_hutt_proj\bin\Debug\asdf.dll");
我需要得到大会的类型。 为了得到类型我需要程序集的命名空间。
Type t = asm.GetType("NAMESPACE.CLASSNAME",false,true);
我怎样才能在上面的行中获得命名空间。?! 为了获得命名空间 ,我需要获取类型..?
Type.Namespace;
即我需要获得可用于获取其类型的程序集的命名空间。
提前致谢
使用Assembly.GetTypes() – 这将获得所有类型的集合,然后您可以获取每个类型的Namespace属性。
然后我猜你可以简单地检查所有类型是否具有相同的Namespace值并使用此值。 否则添加一些其他逻辑来检测要考虑主要的命名空间。
程序集可以包含多个名称空间。 我想你真正想问的是如何在不指定命名空间的情况下从程序集中获取类型。
我不知道是否有更好的方法,但你可以尝试寻找这样的特定类型(添加 – 使用linq;):
myassembly.GetTypes().SingleOrDefault(t => t.Name == "ClassName")
如果在不同的命名空间下有超过1个具有该名称的类(因为Single方法确保只有1),这将有效地抛出。
有关该类的命名空间列表,您可以:
Assembly.Load("ClassName").GetTypes().Select(t => t.Namespace).Distinct();
更新:
如果 assembly name
和assembly namespace
在您的项目中是相同的 ,并且您确定保持主题相同并且您希望获得当前执行的程序集的命名空间, 那么您可以使用:
var namespace = Assembly.GetExecutingAssembly().GetName().Name;
对于你加载的程序集:
var namespace = myAssembly.GetName().Name;
但是如果 assembly name
和assembly namespace
在您的项目中不相同,那么您可以使用这种方式:
// Like @eglasius answer >> // Find all namespaces in the target assembly where a class with the following name is exists: var namespaceList=Assembly.Load("MyClassName").GetTypes().Select(t => t.Namespace).Distinct();
使用Mono / Xamarin,您无权访问“NameSpace”属性。 您可以使用以下代码:
var str = typeof(ATypeInTheAssembly).AssemblyQualifiedName; return str.Split(',')[1].Trim();
Assembly.GetName().Name
将为您提供默认命名空间
要仅使用命名空间,请遵循以下代码:
var assembly = System.Reflection.Assembly.GetAssembly(this.GetType());//Get the assembly object var nameSpace = assembly.GetType().Namespace;//Get the namespace
要么
public string GetNamespace(object obj) { var nameSpace = obj.GetType().Namespace;//Get the namespace return nameSpace; }
获取程序集必须包含几乎一个类(或任何其他类型,如接口),并且它们必须包含在命名空间中,该命名空间必须在程序集命名空间内启动,最短的将是最后一个。
所以,这是我找到的解决方案:
public string GetAssemblyNamespace(Assembly asm) { string ns = @""; foreach (Type tp in asm.Modules.First().GetTypes()) //Iterate all types within the specified assembly. if (ns.Length == 0 ? true : tp.Namespace.Length < ns.Length) //Check whether that's the shortest so far. ns = tp.Namespace; //If it's, set it to the variable. return ns; //Now it is the namespace of the assembly. }
我只是在所需的程序集中找到所有类型,并且我搜索哪个包含在具有最短名称的命名空间中。