简体   繁体   English

C#System.Type是名称空间吗?

[英]C# System.Type is namespace?

System.Type type = Type.GetType("something");

System.Type has no member 'IsNamespace', so how do I tell if the type refers to a namespace? System.Type没有成员'IsNamespace',那么如何确定该类型是否指向名称空间?

The type "something" is not known at compile time. 在编译时类型"something"是未知的。

Type s don't refer to namespaces - they refer to types. Type s不引用名称空间-它们引用类型。 Types have a property which describe which namespace they are in. 类型具有描述它们所在的名称空间的属性。

You could enumerate all the types in an assembly/appdomain and collect/cache the unique namespaces. 您可以枚举程序集/应用程序域中的所有类型,并收集/缓存唯一的名称空间。

HashSet<string> allNamespaces = new HashSet<string>(
    AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Select(t => t.Namespace)
    );

bool isNamespace = allNamespaces.Contains("foo");

It has no member "IsNamespace" because namespaces cannot be represented by Type objects . 它没有成员“ IsNamespace”,因为名称空间无法用Type对象表示 The following line fails to compile: 以下行无法编译:

typeof(System.Linq);

So assuming you have a Type object, you know its not a namespace. 因此,假设您有一个Type对象,就知道它不是名称空间。 With a string like that, GetType should throw if it is just a namespace. 使用这样的字符串,如果它只是一个名称空间,则应该抛出GetType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM