如何检查c#中是否存在命名空间、类或方法

本文关键字:命名空间 存在 方法 是否 何检查 检查 | 更新日期: 2023-09-27 18:17:41

我有一个c#程序,我如何在运行时检查名称空间,类或方法是否存在?此外,如何通过使用它的名称在字符串的形式实例化类?

伪代码:

string @namespace = "MyNameSpace";
string @class = "MyClass";
string method= "MyMEthod";
var y = IsNamespaceExists(namespace);
var x = IsClassExists(@class)? new @class : null; //Check if exists, instantiate if so.
var z = x.IsMethodExists(method);

如何检查c#中是否存在命名空间、类或方法

您可以使用type. gettype (string)来反映类型。如果找不到该类型,GetType将返回null。如果类型存在,那么您可以使用返回的Type中的GetMethodGetFieldGetProperty等来检查您感兴趣的成员是否存在。

更新到您的示例:

string @namespace = "MyNameSpace";
string @class = "MyClass";
string method= "MyMEthod";
var myClassType = Type.GetType(String.format("{0}.{1}", @namespace, @class));
object instance = myClassType == null ? null : Activator.CreateInstance(myClassType); //Check if exists, instantiate if so.
var myMethodExists = myClassType.GetMethod(method) != null;
Console.WriteLine(myClassType); // MyNameSpace.MyClass
Console.WriteLine(myMethodExists); // True

这是最有效和首选的方法,假设类型在mscorlib中当前执行的程序集中(不确定. net Core如何影响这一点,也许是System.Runtime ?),或者您有一个程序集限定的类型名称。如果传递给GetType的字符串参数不满足这三个要求,GetType将返回null(假设没有其他类型意外地与这些要求重叠,哎呀)。


如果没有具有程序集限定名,则需要修改方法以便有限定名或执行搜索,后者可能会慢得多。

如果我们假设你想在所有加载的程序集中搜索该类型,你可以这样做(使用LINQ):

var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
            from type in assembly.GetTypes()
            where type.Name == className
            select type);

当然,可能还不止于此,您可能希望反映可能尚未加载的过引用程序集,等等。

至于确定名称空间,反射并不明确地导出这些名称空间。相反,您必须这样做:

var namespaceFound = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Namespace == namespace
select type).Any()

把它们放在一起,你会得到这样的内容:

var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
                from type in assembly.GetTypes()
                where type.Name == className && type.GetMethods().Any(m => m.Name == methodName)
                select type).FirstOrDefault();
if (type == null) throw new InvalidOperationException("Valid type not found.");
object instance = Activator.CreateInstance(type);

您可以使用Type. gettype (string)方法从字符串中解析类型。例如:

Type myType = Type.GetType("MyNamespace.MyClass");

然后可以使用这个Type实例通过调用GetMethod(String)方法来检查该类型上是否存在一个方法。例如:

MethodInfo myMethod = myType.GetMethod("MyMethod");

如果没有找到给定名称的类型或方法,GetType和GetMethod都返回null,因此您可以通过检查方法调用是否返回null来检查类型/方法是否存在。

最后,你可以使用Activator.CreateInstance(type)实例化你的类型例如:

object instance = Activator.CreateInstance(myType);

一个字:反思。除了名称空间之外,您必须从类型名称中解析它们。

EDIT: Strike that -对于命名空间,您必须使用Type。名称空间属性来确定每个类属于哪个名称空间。