C# - 如何检查命名空间、类或方法是否存在于 C# 中? [英] C# - How to check if namespace, class or method exists in C#?

查看:113
本文介绍了C# - 如何检查命名空间、类或方法是否存在于 C# 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a C# program, how can I check at runtime if a namespace, class, or method exists? Also, how to instantiate a class by using it's name in the form of string?

伪代码:

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);

推荐答案

您可以使用 Type.GetType(string)reflect 一种.如果找不到类型,GetType 将返回 null.如果类型存在,则可以从返回的Type中使用GetMethodGetFieldGetProperty等检查您感兴趣的成员是否存在.

You can use Type.GetType(string) to reflect a type. GetType will return null if the type could not be found. If the type exists, you can then use GetMethod, GetField, GetProperty, etc. from the returned Type to check if the member you're interested in exists.

更新到您的示例:

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(假设没有其他类型意外地与这些要求重叠,哎呀).

This is the most efficient and preferred method, assuming the type is in the currently executing assembly, in mscorlib (not sure how .NET Core affects this, perhaps System.Runtime instead?), or you have an assembly-qualified name for the type. If the string argument you pass to GetType does not satisfy those three requirements, GetType will return null (assuming there isn't some other type that accidentally does overlap those requirements, oops).

如果您没有程序集限定名称,您将需要修正您的方法以便您执行或执行搜索,后者可能要慢得多.

If you don't have the assembly qualified name, you'll either need to fix your approach so you do or perform a search, the latter being potentially much slower.

如果我们假设您确实想在所有加载的程序集中搜索类型,您可以执行以下操作(使用 LINQ):

If we assume you do want to search for the type in all loaded assemblies, you can do something like this (using LINQ):

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

当然,可能还有更多内容,您需要反映可能尚未加载的引用程序集等.

Of course, there may be more to it than that, where you'll want to reflect over referenced assemblies that may not be loaded yet, etc.

至于确定命名空间,反射不会清楚地导出它们.相反,您必须执行以下操作:

As for determining the namespaces, reflection doesn't export those distinctly. Instead, you'd have to do something like:

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

把它们放在一起,你会得到类似的东西:

Putting it all together, you'd have something like:

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);

这篇关于C# - 如何检查命名空间、类或方法是否存在于 C# 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆