dpp*_*dpp 37 c# methods namespaces class
我有一个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);
Run Code Online (Sandbox Code Playgroud)
Hac*_*ese 43
您可以使用Type.GetType(string)来反映类.GetType有方法来发现该类型可用的其他成员,包括方法.
然而,一个技巧是需要GetMethod一个装配限定名称.如果您只使用类名本身,则会假定您引用了当前程序集.
所以,如果你想在所有加载的程序集中找到类型,你可以这样做(使用LINQ):
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
Run Code Online (Sandbox Code Playgroud)
当然,可能还有更多内容,您可能希望反映可能尚未加载的引用程序集等.
至于确定名称空间,反射不会明确地导出这些名称空间.相反,你必须做以下事情:
var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Name == className
select type);
Run Code Online (Sandbox Code Playgroud)
把它们放在一起,你会有类似的东西:
var namespaceFound = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Namespace == namespace
select type).Any()
Run Code Online (Sandbox Code Playgroud)
Mat*_*ing 33
您可以使用Type.GetType(String)方法从字符串中解析Type.例如:
Type myType = Type.GetType("MyNamespace.MyClass");
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用此Type实例通过调用GetMethod(String)方法来检查类型上是否存在方法.例如:
MethodInfo myMethod = myType.GetMethod("MyMethod");
Run Code Online (Sandbox Code Playgroud)
null如果没有找到给定名称的类型或方法,则GetType和GetMethod都会返回,因此您可以通过检查方法调用是否返回null来检查您的类型/方法是否存在.
最后,您可以使用Activator.CreateInstance(Type)实例化您的类型 例如:
object instance = Activator.CreateInstance(myType);
Run Code Online (Sandbox Code Playgroud)