简体   繁体   中英

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?

The type "something" is not known at compile time.

Type s don't refer to namespaces - they refer to types. 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 . The following line fails to compile:

typeof(System.Linq);

So assuming you have a Type object, you know its not a namespace. With a string like that, GetType should throw if it is just a namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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