如何从运行时加载的c#dll程序集中读取方法属性?
我试图在运行时加载一个c#DLL程序集,并使用反射从类方法中查找属性及其包含的值 现在,我有这样的代码来加载程序集并查找属性:如何从运行时加载的c#dll程序集中读取方法属性?,c#,.net,dll,reflection,assemblies,C#,.net,Dll,Reflection,Assemblies,我试图在运行时加载一个c#DLL程序集,并使用反射从类方法中查找属性及其包含的值 现在,我有这样的代码来加载程序集并查找属性: private void ReadAttributes() { Assembly assembly = Assembly.LoadFile(Path.GetFullPath("TestLib.dll")); Type type = assembly.GetType("TestLib.test"); if (type
private void ReadAttributes()
{
Assembly assembly = Assembly.LoadFile(Path.GetFullPath("TestLib.dll"));
Type type = assembly.GetType("TestLib.test");
if (type != null)
{
MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (MethodInfo m in methods)
{
foreach (Attribute a in Attribute.GetCustomAttributes(m, false))
{
Console.WriteLine(a);
foreach (FieldInfo f in a.GetType().GetFields())
{
Console.WriteLine("\t{0}: {1}", f.Name, f.GetValue(a));
}
}
}
}
}
dll文件中的代码如下所示:
[AttributeUsage(AttributeTargets.Method)]
public class Author : Attribute
{
public string name;
public double version;
public Author(string name)
{
this.name = name;
version = 1.0;
}
}
public class Test
{
private string name = "";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
[Author("Andrew")]
public void Message(string mess)
{
Console.WriteLine(mess);
}
[Author("Andrew")]
public void End()
{
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
}
public double Power(double num, int pow)
{
return Math.Pow(num, pow);
}
}
如果我在同一个程序集中使用此代码,而不是动态加载它,那么它就会工作。
但是,当我像这样动态加载程序集时,会加载方法,但不会加载属性
我的代码有什么不正确的地方吗?或者我试图用System.Reflection做的是不可能的吗
注意:
dll不是主程序的依赖项,因此我们无法在编译期间引用属性/类类型。您确定正确的库位于您使用的路径上吗?我猜您的旧版本还没有属性。@AlexeiLevenkov是的,因为如果我在dll中添加了一个额外的函数,我的程序就会发现这个变化。这可能是一个输入错误,但是您的代码块
assembly.GetType(“TestLib.test”)
在测试中应该有一个capitol T。我怀疑这是问题所在。另外,Path.GetFullPath(“TestLib.dll”)
将假定执行程序集的当前工作目录。可能您正在加载的程序集的旧版本没有属性?我会确保这是您期望的路径。这是完整的加载代码还是只是一个片段?实际代码是否实际调用了Assembly.ReflectionOnlyLoad(字符串assemblyFile)
?