我有一个字符串,我要检查,如果它再presents一个正确的命名空间,例如。 System.IO
是好的,但 System.Lol
不是。
I have a string and I want to check if it represents a proper namespace, eg. System.IO
is ok, but System.Lol
is not.
我猜有些反射应该被使用,但我不知道这一点。
I guess some reflection should be used, but I can't figure this out.
有什么想法?
你的问题是当你考虑如何检查是否字符串是一个命名空间是唯一有效的其中的你检查的命名空间。
Your question "How to check if string is a namespace" is only valid when you consider where you are checking for namespaces.
命名空间是prefixes类名称和类作用域的组件。要检查是否命名空间的存在,你需要决定哪些程序集你是ppared仔细看看,找到命名空间的存在,$ P $。
Namespaces are prefixes to class names, and classes are scoped to an assembly. To check whether a namespace exists, you need to decide which assemblies you are prepared to look through to find the existence of the namespace.
一旦你决定哪些程序集你是ppared仔细看看$ P $,你可以通过他们迭代特定名称空间的存在,像这样:
Once you have decided which assemblies you are prepared to look through, you can iterate through them for the existence of a particular namespace like so:
public bool NamespaceExists(IEnumerable<Assembly> assemblies, string ns)
{
foreach(Assembly assembly in assemblies)
{
if(assembly.GetTypes().Any(type => type.Namespace == ns))
return true;
}
return false;
}