获得命名空间,在C#2.0中一个dll类名 [英] Get Namespace, classname from a dll in C# 2.0
问题描述
我会得到dll的动态。我需要加载的DLL并获得命名空间,类名来调用一个方法(方法名是静态的,将永远的OnStart())。
基本上我需要通过加载DLL运行的方法。 。有人可以帮助!
I will get dll's dynamically. I need to load the dll and get the namespace, classname to invoke a method (the method name is static it will be always "OnStart()"). Basically I need to run a method by loading the dll. Can somebody help!!!.
推荐答案
要加载程序集,你可以这样做:
To load the assembly, you would do this:
Assembly assembly = Assembly.LoadFile(@"test.dll");
这假设您在磁盘上的程序集的文件。如果你不这样做,就像如果你从一个数据库作为一个字节数组让他们有对的大会这将帮助你让你加载它后Assembly对象。
This assumes you have the assemblies on disk as files. If you don't, like if you get them from a database as a byte array, there are other methods on the Assembly that will help you give you an Assembly object after loading it.
要通过在装配的所有类,你会遍历做到这一点:
To iterate through all the classes in the assembly, you would do this:
Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass)
{
...
}
}
要查找的OnStart静态方法,你可以这样做:
To find the OnStart static method, you would do this:
Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass)
{
MethodInfo method = type.GetMethod("OnStart",
BindingFlags.Static | BindingFlags.Public);
if (method != null)
{
...
}
}
}
要调用该方法,你可以这样做:
To call the method, you would do this:
Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass)
{
MethodInfo method = type.GetMethod("OnStart",
BindingFlags.Static | BindingFlags.Public);
if (method != null)
{
method.Invoke(null, new Object[0]); // assumes no parameters
break; // no need to look for more methods, unless you got multiple?
}
}
}
如果你需要传递的参数这种方法,你会把他们一个对象数组:
If you need to pass arguments to the method, you would put them in an object array:
Object[] arguments = new Object[] { arg1, arg2, arg3 ... };
method.Invoke(null, arguments);
上面的代码可以使用LINQ为我们找到方法瘫倒在以下几点:
The above code can be collapsed to the following by using Linq to find the method for us:
Assembly assembly = Assembly.LoadFile(@"test.dll");
var method = (from type in assembly.GetTypes()
where type.IsClass
let onStartMethod = type.GetMethod("OnStart",
BindingFlags.Static | BindingFlags.Public)
where onStartMethod != null
select onStartMethod).FirstOrDefault();
if (method != null)
{
method.Invoke(null, new Object[0]); // assumes no parameters
}
这篇关于获得命名空间,在C#2.0中一个dll类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!